通过键盘上的上下左右按键控制一个盒子在页面上移动,并且解决持续按键盒子会有卡顿的问题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>div随键盘控制移动</title>
<style>
#box {
width: 100px;
height: 100px;
background-color: aqua;
position: absolute;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
var box = document.getElementById("box");
var speed = 10;
var dir = 0;
//首先给给document绑定一个键盘事件
document.onkeydown = function(event) {
event = event || window.event;//解决IE兼容问题
dir = event.keyCode;
//测试一下键盘上下左右几个键的值
//console.log(event.keyCode);
}
document.onkeyup = function() {
dir = 0;
}
setInterval(() => {
switch (dir) {
case 37:
box.style.left = box.offsetLeft - speed + "px";
break;
case 38:
box.style.top = box.offsetTop - speed + "px";
break;
case 39:
box.style.left = box.offsetLeft + speed + "px";
break;
case 40:
box.style.top = box.offsetTop + speed + "px";
//console.log(box.style.top);
break;
}
}, 30);//利用定时调用方法,解决卡顿问题
</script>
</body>
</html>