<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>键盘控制移动</title>
<style>
#div1{width: 100px;height: 100px;background: red;position: absolute;}
</style>
<script src="js/move.js"></script>
<script>
window.onload=function () {
var oDiv=document.getElementById('div1');
var left=false;
var right=false;
var top=false;
var button=false;
setInterval(function () {
if(left){
oDiv.style.left=oDiv.offsetLeft-10+'px';
}else if(right){
oDiv.style.left=oDiv.offsetLeft+10+'px';
}else if(top){
oDiv.style.top=oDiv.offsetTop-10+'px';
}else if(button){
oDiv.style.top=oDiv.offsetTop+10+'px';
}
},30)
document.onkeydown=function (ev) {
var oEvent=ev||event;
var keyCode=oEvent.keyCode;
if(keyCode==37){
left=true;
}else if(keyCode==39){
right=true;
}else if(keyCode==38){
top=true;
}else if(keyCode==40){
button=true;
}
}
document.onkeyup=function (ev) {
var oEvent=ev||event;
var keyCode=oEvent.keyCode;
if(keyCode==37){
left=false;
}else if(keyCode==39){
right=false;
}else if(keyCode==38){
top=false;
}else if(keyCode==40){
button=false;
}
}
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>