问题
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;
}
});
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
回答1:
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];
});
Side note: I think when you're using jQuery, e.which
is the more reliable property, as it's normalized for you by jQuery.
回答2:
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
}
});
});
来源:https://stackoverflow.com/questions/19666440/jquery-keyboard-event-handler-press-and-hold