keydown (repetition) breaks when keyup event (for ANOTHER key) is fired

前端 未结 2 685

This is a bit of a weird one so I figure I\'m either missing something obvious or this is a flaw with how these events are implemented in browsers.

Let me first summ

2条回答
  •  囚心锁ツ
    2020-12-11 12:02

    Here is my system for my keyboard input. You can see how the repeating key can be extracted for your own use here. It will allow you to notice held keys and not rely on an Operating system as another answer incorrectly assumed.

    
    var down = [140]; //make an array to cover all the keypresses you should need with a normal keyboard
    
    document.addEventListener('keydown', function(event) {
      if (down[event.keyCode]){
        return;
      } else {
       //do the normal things you do when you get key presses
      down[event.keyCode]=true;
      }
    }, true);
    document.addEventListener('keyup', function(event) {
      down[event.keyCode]=false;
       //do the normal things you do when you get key releases
    }, true);
    
    

    You can just check for the array "down" and the position within it of whatever keycode you want. I use it to prevent keyrepeats for game input. Hope this helps!

提交回复
热议问题