我想为游戏创建一个简单的事件处理程序,这是我的代码
$(document).keydown(function(e){
switch(e.keyCode){
case 65: //left (a)
console.log('left');
break;
case 68: //right (d)
console.log('right');
break;
}
});
问题是,如果我按住一个键,它会在一点点之后触发多次。如何防止此行为?我正在谷歌浏览器上运行我的代码
这是
关键重复。如果你愿意,你可以打败它,记住你已经知道密钥已关闭:
// A map to remember in
var keysdown = {};
// keydown handler
$(document).keydown(function(e){
// Do we already know it's down?
if (keysdown[e.keyCode]) {
// Ignore it
return;
}
// Remember it's down
keysdown[e.keyCode] = true;
// Do our thing
switch(e.keyCode){
case 65: //left (a)
console.log('left');
break;
case 68: //right (d)
console.log('right');
break;
}
});
// keyup handler
$(document).keyup(function(e){
// Remove this key from the map
delete keysdown[e.keyCode];
});
旁注:我认为当你使用jQuery时,e.which
是更可靠的属性,因为它是由jQuery为你规范化的。
var keyPressed = false;
$(document).on('keydown', function(e) {
var key;
if (keyPressed === false) {
keyPressed = true;
key = String.fromCharCode(e.keyCode);
//this is where you map your key
if (key === 'X') {
console.log(key);
//or some other code
}
}
$(this).on('keyup', function() {
if (keyPressed === true) {
keyPressed = false;
console.log('Key no longer held down');
//or some other code
}
});
});