简体   繁体   中英

JavaScript Keyboard Event Not Firing

For some very odd reason when you press keys in the order of forward, spacebar, and left. Left does not fire and returns spacebar instead. Any other combination of three keys works perfectly fine, but not that one. Any clues as to why?

var Ctrl = {
    init: function() {
        window.addEventListener('keydown', this.keyDown, true);
        window.addEventListener('keyup', this.keyUp, true);
    },

    keyDown: function(event) {
        console.log(event.keyCode);

        switch(event.keyCode) {
            case 37: // Left
                Ctrl.left = true;
                break;
            case 39: // Right
                Ctrl.right = true;
                break;
            case 38: // up
                Ctrl.up = true;
                break;
            case 40: // down
                Ctrl.down = true;
                break;
            case 32:
                Ctrl.space = true;
                break;
            default:
                break;
        }
    },

    keyUp: function(event) {

        switch(event.keyCode) {
            case 37: // Left
                Ctrl.left = false;
                break;
            case 39: // Right
                Ctrl.right = false;
                break;
            case 38:
                Ctrl.up = false;
                break;
            case 40:
                Ctrl.down = false;
                break;
            case 32:
                Ctrl.space = false;
                break;
            default:
                break;
        }
    }
};

Maybe one of your keys is activating an unwanted default behavior. You can try to add event.preventDefault(); to your event bindings.

check the jsFiddle

It depends on model of your keyboard. Some keyboards doesn't work with some key combinations. It's normal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM