键盘移动div
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <script type="text/javascript"> 8 /* 9 使div可以根据不同的方向键移动 10 按左键 向左移 11 按右键 向右移 12 按上键 向上移 13 按下键 向下移 14 */ 15 window.onload=function() 16 { 17 var box1=document.getElementById("box1"); 18 //为document绑定一个按键按下的事件 19 document.onkeydown=function(event){ 20 event=event||window.event; 21 //定义一个变量,来表示移动的速度 当用户ctrl以后,速度加快 22 var speed=10; 23 if(event.ctrlKey){ 24 speed=500; 25 } 26 27 switch(event.keyCode){ 28 case 37: 29 box1.style.left=box1.offsetLeft-speed+"px"; 30 break; 31 case 39: 32 box1.style.left=box1.offsetLeft+speed+"px"; 33 break; 34 case 38: 35 box1.style.top=box1.offsetTop-speed+"px"; 36 break; 37 case 40: 38 box1.style.top=box1.offsetTop+speed+"px"; 39 break; 40 } 41 }; 42 }; 43 </script> 44 <style type="text/css"> 45 #box1{ 46 width:100px; 47 height:100px; 48 background-color:red; 49 position:absolute; 50 } 51 </style> 52 <body> 53 <div id="box1"></div> 54 </body> 55 </html>
利用定时器解决卡顿问题
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <script type="text/javascript"> 8 window.onload=function() 9 { 10 var speed=10; 11 var dir=0; 12 //开启一个定时器,来控制div的移动 13 setInterval(function(){ 14 var box1=document.getElementById("box1"); 15 switch(dir){ 16 case 37: 17 box1.style.left=box1.offsetLeft-speed+"px"; 18 break; 19 case 39: 20 box1.style.left=box1.offsetLeft+speed+"px"; 21 break; 22 case 38: 23 box1.style.top=box1.offsetTop-speed+"px"; 24 break; 25 case 40: 26 box1.style.top=box1.offsetTop+speed+"px"; 27 break; 28 } 29 },30); 30 31 document.onkeydown=function(event){ 32 event=event||window.event; 33 if(event.ctrlKey){ 34 speed=50; 35 }else 36 { 37 speed=10; 38 } 39 //使dir等于按键的值 40 dir=event.keyCode; 41 }; 42 document.onkeyup=function(){ 43 dir=0; 44 }; 45 46 }; 47 </script> 48 <style type="text/css"> 49 #box1{ 50 width:100px; 51 height:100px; 52 background-color:red; 53 position:absolute; 54 } 55 </style> 56 <body> 57 <div id="box1"></div> 58 </body> 59 </html>