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

前端 未结 4 2050
半阙折子戏
半阙折子戏 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:38

    There are a few ways, typically involving code-branching for IE's ‘special’ event model.

    One way is to stop keypresses handled further down from bubbling up to the document key handler:

    confirmationbox.onkeydown = function(event) {
        if (event === undefined) event = window.event;
    
        // do something with event.keyCode
    
        if ('stopPropagation' in event) // standards browsers
            event.stopPropagation();
        else if ('cancelBubble' in event) // IE before version 9
            event.cancelBubble = true;
    };
    
    document.onkeydown = ... // will not be called for keydowns inside confirmationbox
    

    Another way would be to check the event target element to see if it's in the box:

    document.onkeydown = function(event) {
        if (event === undefined) event = window.event;
        var target = 'target' in event ? event.target : event.srcElement; // srcElement is for IE<9
    
        if (target === containerbox || isDescendantOf(target, containerbox) {
            // do containerbox stuff
        } else {
            // do other stuff
        }
    };
    
    function isDescendantOf(element, ancestor) {
        while (element = element.parentNode)
            if (element === ancestor)
                return true;
        return false;
    }
    

提交回复
热议问题