How can I avoid autorepeated keydown events in JavaScript?(如何避免 JavaScript 中自动重复的 keydown 事件?)
问题描述
如果用户按住键,则会触发多个 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 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何避免 JavaScript 中自动重复的 keydown 事件?


- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 400或500级别的HTTP响应 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01