使用setInterval来避免误触造成的卡顿、
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style >
#box1{
width: 100px;
height: 100px;
background-color: yellowgreen;
position: absolute;
}
</style>
<script type="text/javascript">
window.onload=function () {
var sup=10;
var dir=0;
//开启一个定时器来控制div的移动
setInterval(function () {
switch (dir) {
case 37:
box1.style.left=box1.offsetLeft-sup+"px";
break;
case 39:
box1.style.left=box1.offsetLeft+sup+"px";
break;
case 38:
box1.style.top=box1.offsetTop-sup+"px";
break;
case 40:
box1.style.top=box1.offsetTop+sup+"px";
break;
};
},30);
document.onkeydown=function (event) {
event=event||window.event;
if(event.ctrlKey){
sup=50;
};
//给dir赋值
dir=event.keyCode;
};
document.onkeyup=function () {
dir=0;
}
}
</script>
</head>
<body>
<div id="box1"></div>
</body>
</html>