In Javascript, how do I tell if a user is pressing two keys at the same time?

前端 未结 4 1992
轻奢々
轻奢々 2021-02-09 13:30

In Javascript, how do I tell if a user is pressing two keys at the same time?

For example, I have drawn a circle in the middle of the screen. I want to move it up while

4条回答
  •  故里飘歌
    2021-02-09 14:23

    Here is what you need to do conceptually (I guess this is called pseudo code):

    Start with something like this:

    var PIXEL_DELTA  = 10; // Distance to move in pixels
    
    var leftPressed  = 0,
        upPressed    = 0,
        downPressed  = 0,
        rightPressed = 0;
    

    Then on every keydown event, test if it the key pressed is left, up, etc and turn its variable from 0 to PIXEL_DELTA.

    On every keyup event, run the same test and turn the correct variable back to 0.

    Then, in your moving code (real code): (This code adapted from Crescent Fresh's awesome example):

    function move() {
      var dot = document.getElementById('dot'),
          deltaX = rightPressed - leftPressed,
          deltaY = downPressed - upPressed;
    
      if(deltaX) {
        dot.style.left = (parseInt(dot.style.left, 10) || 0) + deltaX + 'px';
      }
    
      if (deltaY) {
        dot.style.top = (parseInt(dot.style.top, 10) || 0) + deltaY + 'px';
      }
    }
    

    The browser will (should) fire a separate keydown/keyup event for each key, even if they are "simultaneously" pressed.

    Working Example

    Crescent Fresh put together a full example on JSBin. Be sure to visit the editable version as well to play with the code.

提交回复
热议问题