box1根据键盘上下左右按键移动,要记得给box1开启定位
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title></title>
<style type="text/css">
#box1{
height: 100px;
width: 100px;
background-color: red;
position: absolute;
}
</style>
<script type="text/javascript">
window.onload = function(){
document.onkeydown = function(event){
event = event || window.event;
var speed = 10;
/*37左 38上 39右 40下*/
switch(event.keyCode){
case 37:
box1.style.left = box1.offsetLeft-speed+"px";
break;
case 38:
box1.style.top = box1.offsetTop-speed + "px";
break;
case 39:
box1.style.left =box1.offsetLeft+speed+"px";
break;
case 40:
box1.style.top = box1.offsetTop+speed + "px";
break;
}
};
};
</script>
</head>
<body>
<div id="box1" ></div>
</body>
</html>
用上面的方法在第一下和第二下之间会有卡顿,因此经过定时器改良,不会出现卡顿连贯的移动:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title></title>
<style type="text/css">
#box1{
height: 100px;
width: 100px;
background-color: red;
position: absolute;
}
</style>
<script type="text/javascript">
window.onload = function(){
var dir = 0;
var speed = 10;
//开启定时器控制移动
setInterval(function(){
/*37左 38上 39右 40下*/
switch(dir){
case 37:
box1.style.left = box1.offsetLeft-speed+"px";
break;
case 38:
box1.style.top = box1.offsetTop-speed + "px";
break;
case 39:
box1.style.left =box1.offsetLeft+speed+"px";
break;
case 40:
box1.style.top = box1.offsetTop+speed + "px";
break;
}
},30)
document.onkeydown = function(event){
event = event || window.event;
if(event.ctrlKey){
speed=500;
}else{
speed=10;
}
dir = event.keyCode;
};
//当按键松开,元素不动
document.onkeyup=function(){
dir=0;
}
};
</script>
</head>
<body>
<div id="box1" ></div>
</body>
</html>