简体   繁体   English

向上和向下箭头不适用于 JavaScript 中的 onkeydown

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

I'm building a simple obstacle game and the problem I'm having right now is that I can use the arrow keys to move left and right, but not up and down.我正在构建一个简单的障碍游戏,我现在遇到的问题是我可以使用箭头键左右移动,但不能上下移动。 I don't get why up and down don't work when they have the same logic as left and right.我不明白为什么当它们具有与左右相同的逻辑时,上下不起作用。 I'm fairly new to developing things on my own so go easy on me if it's obvious.我对自己开发东西还很陌生,所以如果很明显,请放轻松。 :) :)

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

})

Your problem is because you're using the deprecated (and ill-defined) KeyboardEvent.keyCode property instead of the standardised code property.您的问题是因为您使用的已弃用(且定义不明确)的KeyboardEvent.keyCode属性,而不是标准化的code属性。

Change your JavaScript to this and it should work:将您的 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 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM