js 键盘移动div、img对象
js 键盘移动div、img对象
1 <html> 2 <script type="text/javascript"> 3 4 var EXtype=""; 5 var len=5; //步长 6 var level=1;//变速倍数 7 var sprite;//div img 或者sprite,移动目标 8 9 //检测浏览器版本 函数 10 function getExplorerVersion(){ 11 12 var Sys = {};//js 所谓的面向对象 对象 13 var ua = navigator.userAgent.toLowerCase(); 14 if (window.ActiveXObject) 15 Sys.ie = ua.match(/msie ([\d.]+)/)[1]; 16 else if (document.getBoxObjectFor) 17 Sys.firefox = ua.match(/firefox\/([\d.]+)/)[1]; 18 else if (window.MessageEvent && !document.getBoxObjectFor) 19 Sys.chrome = ua.match(/chrome\/([\d.]+)/)[1]; 20 else if (window.opera) 21 Sys.opera = ua.match(/opera.([\d.]+)/)[1]; 22 else if (window.openDatabase) 23 Sys.safari = ua.match(/version\/([\d.]+)/)[1]; 24 25 26 27 if(Sys.ie){ document.write('IE: '+Sys.ie); 28 EXtype="IE"; 29 } 30 if(Sys.firefox){ document.write('Firefox: '+Sys.firefox); 31 EXtype="Firefox"; 32 } 33 if(Sys.chrome){ document.write('Chrome: '+Sys.chrome); 34 EXtype="Chrome"; 35 } 36 if(Sys.opera){ document.write('Opera: '+Sys.opera); 37 EXtype="Opera"; 38 } 39 if(Sys.safari){ document.write('Safari: '+Sys.safari); 40 EXtype="Safari"; 41 } 42 43 return EXtype; 44 } 45 //检测浏览器版本 46 getExplorerVersion(); 47 48 49 function onkeyEvent(e) 50 { 51 var kc=""; 52 53 if(EXtype=="IE"){ kc=window.event.keyCode; } 54 else 55 if(EXtype=="Chrome"){ kc= event.which; } 56 57 step(kc); 58 } 59 //move 60 function step(seq) 61 { 62 63 switch(seq) 64 { 65 case 37: 66 sprite.style.left = (parseInt(sprite.style.left) - speed(len)) + "px"; //left 67 break; 68 case 38: 69 sprite.style.top = (parseInt(sprite.style.top) - speed(len)) + "px"; //up 70 break; 71 case 39: 72 sprite.style.left = (parseInt(sprite.style.left) + speed(len)) + "px"; //right 73 break; 74 case 40: 75 sprite.style.top = (parseInt(sprite.style.top) + speed(len)) + "px"; //down 76 break; 77 } 78 } 79 //变速 80 function speed(level) 81 { 82 var steplenvar=len*level; 83 return steplenvar; 84 } 85 //监听 86 document.onkeydown =onkeyEvent; 87 88 function init(){ 89 sprite=document.getElementById("sprite"); 90 } 91 //更换移动对象 92 function clicksprite(e) 93 { 94 var choosediv=e; 95 sprite=document.getElementById(choosediv); 96 } 97 </script> 98 99 <body onload="init()"> 100 <div id="sprite" style="position:absolute; left:0px;top:0px;width:200px;height:100px;color:#000000;background-color:#ffff99;" onclick="clicksprite(this.id)"> </div> 101 102 <div id="sprite1" style="position:absolute; left:100px;top:100px;width:200px;height:100px;color:#000000;background-color:#000fff;" onclick="clicksprite(this.id)"> </div> 103 </body> 104 </html>