Reading multiple simultaneous keyboard inputs using javascript

ⅰ亾dé卋堺 提交于 2019-12-06 08:50:55

问题


I've been noticing some odd behaviour with keyboard input in JavaScript. I may be missing something really obvious here, but are there some kind of rules regarding which keys are allowed to be pressed simultaneously?

I'm using boolean variables to hold state for each of four keys as follows, this allows for many simultaneous key presses (hardware permitting):

var up = false, left = false, right = false, space = false;

function keydown(e) {
    if (e.keyCode == 32)
        space = true;
    if (e.keyCode == 38)
        up = true;
    if (e.keyCode == 37)
        left = true;
    if (e.keyCode == 39)
        right = true;
}

function keyup(e) {
    if (e.keyCode == 32)
        space = false;
    if (e.keyCode == 38)
        up = false;
    if (e.keyCode == 37)
        left = false;
    if (e.keyCode == 39)
        right = false;
}

On two machines I've tried the following jsfiddle allows you to press space, up and right simultaneously, but not space, up and left, for example. On those two machines it's doing the same in Chrome, FF and IE. On a third machine it works flawlessly and I can hold all 4 keys simultaneously.

Now presumably this is hardware related, but my main question is why there is a difference in the operation of the left and the right keys? It seems inconsistent and I'm sure there is a valid reason why it's the way it is.

http://jsfiddle.net/SYs5b/

(You have to click within the results pane to get the events firing)


回答1:


In order to save money, keyboard manufacturers often put many keys on the same bus. This prevents multiple keys in the same region of the keyboard from being pressed simultaneously. Sometimes it even prevents more than 2 keys at all from across the whole keyboard being pressed at once. Often the shift, ctrl, and alt keys are not within this limitation, so you can hold shift and press 2 other keys at once and it will still work fine.

Even high-end gaming keyboards often have a similar hardware limitation, although the cap is much higher so that it is unlikely to be reached during the normal course of gaming.

This is also known as "ghosting", when keys you press seem not to register.



来源:https://stackoverflow.com/questions/21634752/reading-multiple-simultaneous-keyboard-inputs-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!