简体   繁体   English

JavaScript键盘事件未触发

[英]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. Left不会触发,而是返回空格键。 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(); 您可以尝试添加event.preventDefault(); to your event bindings. 您的事件绑定。

check the jsFiddle 检查jsFiddle

It depends on model of your keyboard. 这取决于您的键盘型号。 Some keyboards doesn't work with some key combinations. 某些键盘不适用于某些按键组合。 It's normal. 这是正常的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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