代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>键盘事件</title>
<style>
*{
margin:0px;
padding:0px;
}
div{
width:320px;
height:161px;
margin:100px 40%;
position:absolute;
}
img{
width:300px;
height:161px;
}
</style>
</head>
<body>
<divid="div" style="top: 0px; left: 0px;">
<imgsrc="img/000/307856_300.jpg" alt="">
</div>
<script>
var t = 0;
var l = 0;
window.οnkeydοwn= function(e){
var e= e||window.Event;
varxDiv = document.getElementById("div");
t =parseInt(xDiv.style.top);
f =parseInt(xDiv.style.left);
if(e.keyCode==38|| e.keyCode==87 || e.keyCode==73 || e.keyCode==101){
xDiv.style.top= t-100+"px";
}elseif(e.keyCode==37 || e.keyCode==65 || e.keyCode==74 || e.keyCode==97){
xDiv.style.left= f-100+"px";
}elseif(e.keyCode==39 || e.keyCode==68 || e.keyCode==76 || e.keyCode==99){
xDiv.style.left= f+100+"px";
}elseif(e.keyCode==40 || e.keyCode==83 || e.keyCode==75 || e.keyCode==98){
xDiv.style.top= t+100+"px";
}
}
</script>
</body>
</html>
效果: