jQuery键盘事件处理程序按住

我想为游戏创建一个简单的事件处理程序,这是我的代码

$(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 } }); });