gpt4 book ai didi

javascript - 使用键盘箭头向上和向下移动 div

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

我希望能够使用键盘箭头移动 ID 为 cube 的 div。向左和向右移动正常,但我无法让它上​​下移动。

var output=document.getElementById("output");
var cube=document.getElementById("cube");
var left=0;
var top=0;

document.addEventListener("keydown", function(e) {
output.innerHTML='Key code: ' + e.which + '<br />' + 'Key Name: ' + e.key;
var key=e.which;

switch (key) {
case 38: //arrow up
top = top - 10;
cube.style.top= top + "px";
cube.style.background="green";
break;
case 40: //arrow down
top = top + 10;
cube.style.top= top + "px";
cube.style.background="#14B4AA";
break;
case 39: //arrow right
left = left + 10;
cube.style.left= left + "px";
cube.style.background="blue";
break;
case 37: //arrow left
left = left - 10;
cube.style.left= left + "px";
cube.style.background="brown";
break;
}
});

...

最佳答案

你不能有一个名为“top”的全局变量。

top is a host object, it points to the outermost window object and is most useful when used from within a frame https://humanwhocodes.com/blog/2007/06/03/javascript-variable-names-you-shouldn-t-use/

如果变量名被更改,或者如果它的作用域不是窗口(例如在事件监听器中),您的代码将正常工作。

var output=document.getElementById("output");
var cube=document.getElementById("cube");
var left=0;
var t=0;

document.addEventListener("keydown", function(e) {
output.innerHTML='Key code: ' + e.which + '<br />' + 'Key Name: ' + e.key;
var key=e.which;
e.preventDefault(); // used to prevent window scroll on up/down keys

switch (key) {
case 38: //arrow up
t = t - 10;
cube.style.top= t + "px";
cube.style.background="green";
break;
case 40: //arrow down
t = t + 10;
cube.style.top= t + "px";
cube.style.background="#14B4AA";
break;
case 39: //arrow right
left = left + 10;
cube.style.left= left + "px";
cube.style.background="blue";
break;
case 37: //arrow left
left = left - 10;
cube.style.left= left + "px";
cube.style.background="brown";
break;
}
});
#cube {position: absolute}
<div id="cube">CUBE</div>
<div id="output">OUTPUT</div>
(请注意,在运行上面的代码时,您必须在代码段内部单击以获取到达它的关键事件)

关于javascript - 使用键盘箭头向上和向下移动 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55764495/

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