js 键盘移动div、img对象

 <html>
<script type="text/javascript"> var EXtype="";
var len=5; //步长
var level=1;//变速倍数
var sprite;//div img 或者sprite,移动目标 //检测浏览器版本 函数
function getExplorerVersion(){ var Sys = {};//js 所谓的面向对象 对象
var ua = navigator.userAgent.toLowerCase();
if (window.ActiveXObject)
Sys.ie = ua.match(/msie ([\d.]+)/)[1];
else if (document.getBoxObjectFor)
Sys.firefox = ua.match(/firefox\/([\d.]+)/)[1];
else if (window.MessageEvent && !document.getBoxObjectFor)
Sys.chrome = ua.match(/chrome\/([\d.]+)/)[1];
else if (window.opera)
Sys.opera = ua.match(/opera.([\d.]+)/)[1];
else if (window.openDatabase)
Sys.safari = ua.match(/version\/([\d.]+)/)[1]; if(Sys.ie){ document.write('IE: '+Sys.ie);
EXtype="IE";
}
if(Sys.firefox){ document.write('Firefox: '+Sys.firefox);
EXtype="Firefox";
}
if(Sys.chrome){ document.write('Chrome: '+Sys.chrome);
EXtype="Chrome";
}
if(Sys.opera){ document.write('Opera: '+Sys.opera);
EXtype="Opera";
}
if(Sys.safari){ document.write('Safari: '+Sys.safari);
EXtype="Safari";
} return EXtype;
}
//检测浏览器版本
getExplorerVersion(); function onkeyEvent(e)
{
var kc=""; if(EXtype=="IE"){ kc=window.event.keyCode; }
else
if(EXtype=="Chrome"){ kc= event.which; } step(kc);
}
//move
function step(seq)
{ switch(seq)
{
case 37:
sprite.style.left = (parseInt(sprite.style.left) - speed(len)) + "px"; //left
break;
case 38:
sprite.style.top = (parseInt(sprite.style.top) - speed(len)) + "px"; //up
break;
case 39:
sprite.style.left = (parseInt(sprite.style.left) + speed(len)) + "px"; //right
break;
case 40:
sprite.style.top = (parseInt(sprite.style.top) + speed(len)) + "px"; //down
break;
}
}
//变速
function speed(level)
{
var steplenvar=len*level;
return steplenvar;
}
//监听
document.onkeydown =onkeyEvent; function init(){
sprite=document.getElementById("sprite");
}
//更换移动对象
function clicksprite(e)
{
var choosediv=e;
sprite=document.getElementById(choosediv);
}
</script> <body onload="init()">
<div id="sprite" style="position:absolute; left:0px;top:0px;width:200px;height:100px;color:#000000;background-color:#ffff99;" onclick="clicksprite(this.id)"> </div> <div id="sprite1" style="position:absolute; left:100px;top:100px;width:200px;height:100px;color:#000000;background-color:#000fff;" onclick="clicksprite(this.id)"> </div>
</body>
</html>
04-01 17:42