<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#div1 {width: 100px; height: 100px; background: red; position: absolute;}
</style>
<script>
window.onload = function() {
var oDiv = document.getElementById('div1');
document.onkeydown = function(ev) { //键盘按键时发生的函数
var ev = ev || event; //事件的浏览器兼容性
switch(ev.keyCode) { //判断键盘按键的编码
case 37:
oDiv.style.left = oDiv.offsetLeft - 10 + 'px'; //如果是左键左移
break; //退出不执行后面的
case 38:
oDiv.style.top = oDiv.offsetTop - 10 + 'px'; //如果是上键上移
break;
case 39:
oDiv.style.left = oDiv.offsetLeft + 10 + 'px'; //右键右移
break;
case 40:
oDiv.style.top = oDiv.offsetTop + 10 + 'px'; //下键下移
break;
}
}
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>