首页 > 解决方案 > 使用键盘箭头向上和向下移动 div

问题描述

我希望能够cube使用键盘箭头移动带有 id 的 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;
    }
});

...

标签: javascriptcsshtml

解决方案


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

top 是一个宿主对象,它指向最外层的窗口对象,在框架内使用时最有用 https://humanwhocodes.com/blog/2007/06/03/javascript-variable-names-you-shouldn-t -利用/

如果变量名称被更改,或者如果它的范围不是窗口(例如在事件侦听器内),您的代码可以正常工作。

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>
(请注意,在运行上述代码时,您必须在代码段内单击以获取关键事件以到达它)


推荐阅读