What is the best way to handle multiple key events in Javascript?

前端 未结 4 2043
半阙折子戏
半阙折子戏 2021-02-08 11:24

Pressing space bar in game will make a character shoot, pressing space bar when a confirmation box is shown will make this box disappear and pressing space bar in a highscore fo

4条回答
  •  一生所求
    2021-02-08 11:35

    Attach event listeners to individual elements instead of the entire document.

    document.getElementById('highscore').onkeypress = function(keyEvent) {
          if (is_spacebar(keyEvent)) //Do something...
    };
    
    document.getElementById('game').onkeypress = function(keyEvent) {
          if (is_spacebar(keyEvent)) //Do something else...
    };
    

    This is a simplistic example. You will probably have to deal with event bubbling which can be controlled when using addEventListener() to attach functions to events. Given browser (IE) compatibility issues involving this, some JS library should be used to deal with events.

提交回复
热议问题