How to take keyboard input in JavaScript?

前端 未结 5 2044
醉梦人生
醉梦人生 2020-12-02 08:50

I want to take keyboard input in JavaScript, where arrow keys, when pressed, will result in the change in shape of a particular shape. How do I take the input of any of the

5条回答
  •  孤城傲影
    2020-12-02 09:22

    You should register an event handler on the window or any element that you want to observe keystrokes on, and use the standard key values instead of keyCode. This modified code from MDN will respond to keydown when the left, right, up, or down arrow keys are pressed:

    window.addEventListener("keydown", function (event) {
      if (event.defaultPrevented) {
        return; // Do nothing if the event was already processed
      }
    
      switch (event.key) {
        case "ArrowDown":
          // code for "down arrow" key press.
          break;
        case "ArrowUp":
          // code for "up arrow" key press.
          break;
        case "ArrowLeft":
          // code for "left arrow" key press.
          break;
        case "ArrowRight":
          // code for "right arrow" key press.
          break;
        default:
          return; // Quit when this doesn't handle the key event.
      }
    
      // Cancel the default action to avoid it being handled twice
      event.preventDefault();
    }, true);
    // the last option dispatches the event to the listener first,
    // then dispatches event to window

提交回复
热议问题