問題描述
如果用戶按住鍵,則會觸發多個 keydown 事件.出于可用性原因,我需要使用 keydown,而不是 keyup,但我想避免這種情況.我的相關代碼如下:
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;
}
});
因此,例如,當用戶按住向下鍵時,會多次觸發 goDown().即使用戶按住鍵,我也希望它只觸發一次.
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
檢測事件是否重復.然后,您可以在允許處理程序第二次執行之前等待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;
});
這篇關于如何避免 JavaScript 中自動重復的 keydown 事件?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!