//------------存放四个变量控制四个方向,可以进行斜向位移
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>freeRemove</title> 6 </head> 7 <style type="text/css"> 8 #tank{ 100px;height: 100px;position: absolute;background: red;} 9 </style> 10 <script type="text/javascript"> 11 window.onload=function(){ 12 var timer=["up","down","left","right"]; 13 var keyId; 14 oTank=document.getElementById('tank'); 15 function clear(){ 16 clearInterval(timer[keyId]); 17 } 18 document.onkeydown=function(ev){ 19 oEvent=ev||event; 20 switch(oEvent.keyCode){ 21 case 37:clearInterval(timer[0]);timer[0]=setInterval(function(){oTank.style.left=oTank.offsetLeft-5+'px';},10);break; 22 case 38:clearInterval(timer[1]);timer[1]=setInterval(function(){oTank.style.top=oTank.offsetTop-5+'px';},10);break; 23 case 39:clearInterval(timer[2]);timer[2]=setInterval(function(){oTank.style.left=oTank.offsetLeft+5+'px';},10);break; 24 case 40:clearInterval(timer[3]);timer[3]=setInterval(function(){oTank.style.top=oTank.offsetTop+5+'px';},10);break; 25 } 26 } 27 document.onkeyup=function(ev){ 28 oEvent=ev||event; 29 keyId=oEvent.keyCode-37; 30 switch(oEvent.keyCode){ 31 case 37:clear();break; 32 case 38:clear();break; 33 case 39:clear();break; 34 case 40:clear();break; 35 default: break; 36 } 37 } 38 } 39 </script> 40 <body> 41 <div id="tank"></div> 42 </body> 43 </html>