最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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 the user holds down the up arrow and right while the user holds down the right arrow. That part works easy. If user holds both the up and right arrows, I want to move the circle diagonally, up and to the right.

It doesn't look like this possible with basic Javascript event handling, but surely someone has figured out a work around/hack/improvement.

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 the user holds down the up arrow and right while the user holds down the right arrow. That part works easy. If user holds both the up and right arrows, I want to move the circle diagonally, up and to the right.

It doesn't look like this possible with basic Javascript event handling, but surely someone has figured out a work around/hack/improvement.

Share Improve this question edited Jan 7, 2010 at 4:31 Doug Neiner 66.2k13 gold badges110 silver badges118 bronze badges asked Jan 7, 2010 at 4:29 Chad DeShonChad DeShon 4,7826 gold badges30 silver badges29 bronze badges 2
  • How did you draw circle in the middle of screen with Javascript? If you using some libraries please specify it, key handling should be done inside that library. – YOU Commented Jan 7, 2010 at 4:33
  • I used Raphael [raphaeljs.], which is a svg library. I don't think it provides any key input functionality. – Chad DeShon Commented Jan 7, 2010 at 4:36
Add a ment  | 

4 Answers 4

Reset to default 8

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.

Javascript has onkeydown, and onkeyup events. You can simple fiddle a bit onkeydown for left arrow, and fiddle another bit for the up arrow. On keyup, fiddle the respective bit back.

var leftPressed,
    upPressed,
    rightPressed,
    downPressed;

var milli = 100;

window.addEventListener('onkeydown', function(e) {
    switch(e.keycode) {
        case 37: //left
            leftPressed = true;
        case 38: //up
            upPressed = true;
        case 39: //right
           rightPressed = true;
        case 40: //down
            downPressed = true;
        default:
            break;
    }
});

window.addEventListener('onkeyup', function(e) {
    switch(e.keycode) {
        case 37: //left
            leftPressed = false;
        case 38: //up
            upPressed = false;
        case 39: //right
           rightPressed = false;
        case 40: //down
            downPressed = false;
        default:
            break;
    }

});

function moveCircle() {
    if(leftPressed && !rightPressed) {
        // move left
    }
    if(rightPressed && !leftPressed) {
        // move right
    }
    if(upPressed && !downPressed) {
        // move up
    }
    if(downPressed && !upPressed) {
        // move down
    }
}

setInterval(moveCircle, milli);

Maybe you can do it by keeping track of keydown and keyup event for each key and you'll know if two keys are being held at the same time.

Sample pseudo-code:

var keydown = {};

function onkeydown(event) {
   keydown[event.key] = true;
}

function onkeyup(event) {
   keydown[event.key] = false;
}

// in some function at some other places

if (keydown['up'] && keydown['right']) {
  move_diagonal('up', 'right');
}
elseif (keydown['up'] && keydown['left']) {
  move_diagonal('up', 'left');
}
elseif .. blah blah

Javascript keyboard events fire on keypress and keydown, but don't contain the additional keymask info to determine if other keys are pressed at the same time.

发布评论

评论列表(0)

  1. 暂无评论