jQuery键盘事件处理器按住 [英] jQuery keyboard event handler press and hold
本文介绍了jQuery键盘事件处理器按住的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为游戏创建一个简单的事件处理程序,这里是我的代码
i want to create a simple event handler for a game, here's my code
$(document).keydown(function(e){
switch(e.keyCode){
case 65: //left (a)
console.log('left');
break;
case 68: //right (d)
console.log('right');
break;
}
});
问题是如果我按住一个键,稍后会触发多次。
我该如何防止这种行为?我在Google Chrome上运行我的代码
the problem is that if i press and hold a key, after a little it triggers multiple times. how can i prevent this behaviour? i'm running my code on google chrome
推荐答案
这是重点。您可以通过记住您已经知道钥匙已经关闭,您可以击败它:
This is key repeat. You can defeat it if you want to, by remembering that you already know the key is down:
// 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进行标准化。
Side note: I think when you're using jQuery, e.which
is the more reliable property, as it's normalized for you by jQuery.
这篇关于jQuery键盘事件处理器按住的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文