代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>键盘控制方块移动</title>
<style>
#box{
width: 50px;
height: 50px;
background-color: green;
position: relative;
left: 50px;
top: 50px;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
var div=document.getElementById('box');
var s=0,left=0,right=0,bottom=0;
var timer=null,x=50,y=50;
timer=setInterval(function(){
if (left==1) {
x-=5;
div.style.left=x+'px';
}
if (right==1) {
x+=5;
div.style.left=x+'px';
}
if (s==1) {
y-=5;
div.style.top=y+'px';
}
if (bottom==1) {
y+=5;
div.style.top=y+'px';
}
},20)
document.onkeydown=function(ev){
var e=ev||window.event;
switch(e.keyCode){
case 37:
left=1;
break;
case 38:
s=1;
break;
case 39:
right=1;
break;
case 40:
bottom=1;
break;
}
}
document.onkeyup=function(ev){
var e=ev||window.event;
switch(e.keyCode){
case 37:
left=0;
break;
case 38:
s=0;
break;
case 39:
right=0;
break;
case 40:
bottom=0;
break;
}
}
</script>
</body>
</html>
项目效果:
项目地址: