我有一个用于捕获和注册箭头键输入的系统。它一直有效。只要按下两个或更少的键,它就会正确记录是否同时按下多个键。如果同时按下第三个或第四个,它将停止触发 keydown 事件。请查看这个 jsFiddle并查看控制台的输出。
这是浏览器设置的限制还是我的代码错误?任何帮助将非常感激。
这是代码:
var keysPressed = {
37: false,
38: false,
39: false,
40: false
};
var LEFT = 'left';
var RIGHT = 'right';
var UP = 'up';
var DOWN = 'down';
var ON = '_on';
var OFF = '_off'
document.addEventListener('keydown', function(evt){
var keycode = evt.keyCode;
if(!checkKeyPressed(keycode)){
keysPressed[keycode] = true;
switch(keycode){
case 37:
registerInput(LEFT+ON);
break;
case 38:
registerInput(UP+ON);
break;
case 39:
registerInput(RIGHT+ON);
break;
case 40:
registerInput(DOWN+ON);
break;
default:
break;
}
}
});
document.addEventListener('keyup', function(evt){
var keycode = evt.keyCode;
if(checkKeyPressed(keycode)){
keysPressed[keycode] = false;
switch(keycode){
case 37:
registerInput(LEFT+OFF);
break;
case 38:
registerInput(UP+OFF);
break;
case 39:
registerInput(RIGHT+OFF);
break;
case 40:
registerInput(DOWN+OFF);
break;
default:
break;
}
}
});
function checkKeyPressed(keycode){
if (keysPressed === null) {
return false;
} else return keysPressed[keycode];
}
function registerInput(inputType){
console.log(keysPressed);
//Game.Engine.playerInput(inputType);
}