js按键键盘键实现物体旋转效果
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 <style> 7 8 *{ 9 margin: 0; 10 padding: 0; 11 } 12 .div{ 13 width: 100px; 14 height: 100px; 15 background-color: aqua; 16 position: absolute; 17 } 18 19 20 </style> 21 22 <script> 23 28 29 //文档就绪函数 30 onload=function(e){ 31 //获取div 32 var div=document.getElementsByClassName("div")[0]; 33 34 //键盘点击事件 35 document.addEventListener("keydown",key); 36 //键盘点解旋转 37 var x=0; 38 function key(e) { 39 if (e.keyCode == 39) { 40 x += 5; 41 var p = x + "deg"; 42 div.style.transform = "rotate(" + p + ")"; 43 } else if (e.keyCode == 37) { 44 x -= 5; 45 var p = x + "deg"; 46 div.style.transform = "rotate(" + p + ")"; 47 } 48 } 49 50 } 51 52 53 54 </script> 55 </head> 56 <body> 57 <div class="div" style="top: 0px;left: 0px"> 58 59 </div> 60 </body> 61 </html>