<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.demo{
position: absolute;
width:100px;
height: 100px;
background: #ccc;
}
</style>
</head>
<body>
<div id="demo" class="demo"></div>
<script>
var demo=document.getElementById('demo');
document.οnkeyup=function(ev){ //键盘事件(按键松开时发生)
var e=ev||event;
switch(e.keyCode){ // keyCode:键码值
case 37:
demo.style.left=(demo.offsetLeft-5)+"px";break; // 偏移
case 39:
demo.style.left=(demo.offsetLeft+5)+"px";break;
case 38:
demo.style.top=(demo.offsetTop-5)+"px";break;
case 40:
demo.style.top=(demo.offsetTop+5)+"px";break;
}
}
</script>
</body>
</html>