我有以下代码,我想移动一个框我的按下箭头(在本例中为左箭头)但只向左属性添加一次。如果我多次按下左箭头,它会保持在同一个位置。想不通为什么..
const box = document.querySelector('div');
const body = document.querySelector('body');
body.addEventListener('keydown', move);
function move(event) {
let ddd = event.which || event.keyCode;
let left = 0;
box.style.position = 'absolute';
if(ddd === 37) {
left += 5;
box.style.left = left + 'px';
}
}
最佳答案
那是因为你每次都在重置 left
的值。将 left
存储在 move
之外,以防止重置它。
const box = document.querySelector('div');
const body = document.querySelector('body');
let left = 0;
body.addEventListener('keydown', move);
function move(event) {
let ddd = event.which || event.keyCode;
box.style.position = 'absolute';
if(ddd === 37) {
left += 5;
box.style.left = left + 'px';
}
}
关于javascript - 它不会增加位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56382126/