0. 效果图
1. 实现代码
html
<head>
<style>
.box {
position: absolute;
width: 100px;
height: 100px;
top: 100px;
left: 100px;
background-color: orange;
}
</style>
</head>
<body>
<div class="box" id="box">
</div>
</body>
javascript
var oBox = document.getElementById('box');
var t = 100;
var l = 100;
document.onkeydown = function (e) {
console.log(e.keyCode);
switch (e.keyCode) {
case 37:
l -= 3;
break;
case 38:
t -= 3;
break;
case 39:
l += 3;
break;
case 40:
t += 3;
break;
default:
break;
}
oBox.style.left = l + 'px';
oBox.style.top = t + 'px';
}