我想为游戏创建一个简单的事件处理程序,这是我的代码
$(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 上运行我的代码
这是关键重复。如果你愿意的话,你可以打败它,只要记住你已经知道钥匙按下了:
// 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 为您标准化 http://api.jquery.com/category/events/event-object/.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)