我试图用箭头键在div内移动一个div。但是为了使它连续工作,它需要一个setInterval计时器。我相信因此,浏览器会产生不必要的负担。我希望定时器仅在按下箭头键保持时才有效,否则不会。
window.addEventListener("keydown", checkKeyPressed);
window.addEventListener("keyup", checkKeyReleased);
var key = [];
function checkKeyPressed(e) {
key[e.keyCode] = true;
}
function checkKeyReleased(e) {
key[e.keyCode] = false;
}
function moveLeft() {
var pos = document.getElementById("box").style.left;
document.getElementById("box").style.left = parseInt(pos) - 5 + "px";
}
function moveUp() {
var pos = document.getElementById("box").style.top;
document.getElementById("box").style.top = parseInt(pos) - 5 + "px";
}
function moveRight() {
var pos = document.getElementById("box").style.left;
document.getElementById("box").style.left = parseInt(pos) + 5 + "px";
}
function moveDown() {
var pos = document.getElementById("box").style.top;
document.getElementById("box").style.top = parseInt(pos) + 5 + "px";
}
function move() {
var t = parseInt(document.getElementById("box").style.top);
var l = parseInt(document.getElementById("box").style.left);
if (key[37] && l !== 0) {
moveLeft();
}
if (key[38] && t !== 0) {
moveUp();
}
if (key[39] && l !== 400) {
moveRight();
}
if (key[40] && t !== 400) {
moveDown();
}
}
var timer = setInterval(move, 1);
#container {
width: 500px;
height: 500px;
position: relative;
background-color: orange;
}
#box {
width: 100px;
height: 100px;
position: absolute;
background-color: red;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles/style.css">
</head>
<body>
<div id="container">
<div id="box" style="top: 0; left: 0;"></div>
</div>
<script src="scripts/script.js"></script>
</body>
</html>