gpt4 book ai didi

javascript - 它不会增加位置

转载 作者:太空宇宙 更新时间:2023-11-04 00:49:06 25 4
gpt4 key购买 nike

我有以下代码,我想移动一个框我的按下箭头(在本例中为左箭头)但只向左属性添加一次。如果我多次按下左箭头,它会保持在同一个位置。想不通为什么..

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com