問(wèn)題描述
如果用戶按住鍵,則會(huì)觸發(fā)多個(gè) keydown 事件.出于可用性原因,我需要使用 keydown,而不是 keyup,但我想避免這種情況.我的相關(guān)代碼如下:
If the user holds down the key, multiple keydown events are fired. For usability reasons I need to use keydown, not keyup, but I want to avoid this situation. My relevant code is the following:
$(document).keydown(function(e) {
var key = 0;
if (e == null) { key = event.keyCode;}
else { key = e.which;}
switch(key) {
case config.keys.left:
goLeft();
break;
case config.keys.up:
goUp();
break;
case config.keys.right:
goRight();
break;
case config.keys.down:
goDown();
break;
case config.keys.action:
select();
break;
}
});
因此,例如,當(dāng)用戶按住向下鍵時(shí),會(huì)多次觸發(fā) goDown().即使用戶按住鍵,我也希望它只觸發(fā)一次.
So when the user holds down the down key, for example, goDown() is fired multiple times. I would like it to fire just once even if the user holds the key down.
推薦答案
使用 event.repeat
檢測(cè)事件是否重復(fù).然后,您可以在允許處理程序第二次執(zhí)行之前等待keyup".
Use event.repeat
to detect whether or not the event is repeating. You could then wait for "keyup" before allowing the handler to execute a second time.
var allowed = true;
$(document).keydown(function(event) {
if (event.repeat != undefined) {
allowed = !event.repeat;
}
if (!allowed) return;
allowed = false;
//...
});
$(document).keyup(function(e) {
allowed = true;
});
$(document).focus(function(e) {
allowed = true;
});
這篇關(guān)于如何避免 JavaScript 中自動(dòng)重復(fù)的 keydown 事件?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!