在 JavaScript 中,向上和向下箭头不能与 onkeydown 一起使用

Up and Down Arrows Aren't Working with onkeydown in JavaScript

我正在构建一个简单的障碍游戏,我现在遇到的问题是我可以使用箭头键左右移动,但不能上下移动。我不明白为什么当上下具有与左右相同的逻辑时它们不起作用。我对自己开发东西还很陌生,所以如果很明显的话,请放轻松。 :)

document.addEventListener("DOMContentLoaded", () => {
  // Grab the elements from the HTML
  const floppy = document.getElementById("floppyDisk");
  const gameBoard = document.querySelector(".gameBoard");

  let userScore = document.getElementById("userScore");
  let highscore = document.getElementById("highscore");

  // Set up variables to be used later
  let floppyPosX = 0;
  let floppyPosY = 0;
  let left = 20;
  let top = 190;

  // Use the arrows to move the floppy disk
  function moveFloppy(e) {
    if(e.keyCode == 39) {
      left += 2;
      floppy.style.left = floppyPosX + left + "px";
    }
    if(e.keyCode == 37) {
      left -= 2;
      floppy.style.left = floppyPosX + left + "px";
    }
    if(e.keycode == 38) {
      top += 2;
      floppy.style.top = floppyPosY + top + "px";
    }
    if(e.keycode == 40) {
      top -= 2;
      floppy.style.top = floppyPosY + top + "px";
    }
  }

  // Invoke the moveFloppy function
  document.onkeydown = moveFloppy;
  
  // Generate Obstacles
  
    // Function to move the obstacles

    // Set function to repeat


  // Call the function to generate the obstacles

})

你的问题是因为你使用的是 the deprecated (and ill-defined) KeyboardEvent.keyCode property 而不是标准化的 code 属性.

将您的 JavaScript 更改为此,它应该可以工作:

function moveFloppy(e) {
    switch(e.code) {
    case 'ArrowLeft':
        left += 2;
        floppy.style.left = floppyPosX + left + "px";
        break;
    case 'ArrowRight':
        left -= 2;
        floppy.style.left = floppyPosX + left + "px";
        break;
    case 'ArrowUp':
        top += 2;
        floppy.style.top = floppyPosY + top+ "px";
        break;
    case 'ArrowDown':
        top -= 2;
        floppy.style.top = floppyPosY + top + "px";
        break;
    default:
        // TODO: Play a fart sound.
        break;
    }
}

document.addEventListener( 'keydown', moveFloppy );