<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>键盘控制DIV移动</title>
<script type="text/javascript">
function keyEvent(event) {
var distance = document.getElementById("move");
switch(event.keyCode){
case 37:{
distance.style.left = distance.offsetLeft-50+"px";
break;
}
case 38:{
distance.style.top = distance.offsetTop-50+"px";
break;
}
case 39:{
distance.style.left = distance.offsetLeft+50+"px";
break;
}
case 40:{
distance.style.top = distance.offsetTop+50+"px";
break;
}
}
}
</script>
<style type="text/css">
#move {
width: 100px;
height: 100px;
border: 1pxsolid #000;
background: #EAEAEA;
position: absolute;
}
</style>
</head>
<body onkeydown="keyEvent(event)">
<div id="move"></div>
</body>
</html>