向上和向下箭头无法在JavaScript中使用onkeydown

问题描述

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

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 );