查找 x 轴位置以使元素移动
Find x-axis location to make an element move
我试图让一个元素在用户按下“a”时在 X 轴上向后移动。但是,我不知道每次用户按下那个键时如何让它移动得更远:(。我是 JS 的新手
document.addEventListener("keypress", function (e) {
let moveBy = 20;
if (e.key === "a") {
moveBy++;
element.style.webkitTransform = `translateX(-${moveBy}px)`;
}
}
谢谢!
在函数外定义 moveBy 并在每次按键时递增
const element = document.querySelector('div');
let moveBy = 20;
document.addEventListener("keypress", function (e) {
if (e.key === "a") {
moveBy++;
element.style.webkitTransform = `translateX(-${moveBy}px)`;
moveBy+=20
}
})
div {
width: 200px;
height: 200px;
background: red;
}
<div></div>
我试图让一个元素在用户按下“a”时在 X 轴上向后移动。但是,我不知道每次用户按下那个键时如何让它移动得更远:(。我是 JS 的新手
document.addEventListener("keypress", function (e) {
let moveBy = 20;
if (e.key === "a") {
moveBy++;
element.style.webkitTransform = `translateX(-${moveBy}px)`;
}
}
谢谢!
在函数外定义 moveBy 并在每次按键时递增
const element = document.querySelector('div');
let moveBy = 20;
document.addEventListener("keypress", function (e) {
if (e.key === "a") {
moveBy++;
element.style.webkitTransform = `translateX(-${moveBy}px)`;
moveBy+=20
}
})
div {
width: 200px;
height: 200px;
background: red;
}
<div></div>