如何避免 JavaScript 中自动重复的 keydown 事件?

How can I avoid autorepeated keydown events in JavaScript?(如何避免 JavaScript 中自动重复的 keydown 事件?)
本文介绍了如何避免 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 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I can get a text of all the cells of the table using testcafe(如何使用 testcafe 获取表格中所有单元格的文本)
node_modules is not recognized as an internal or external command(node_modules 未被识别为内部或外部命令)
How can I create conditional test cases using Protractor?(如何使用 Protractor 创建条件测试用例?)
PhantomJS and clicking a form button(PhantomJS 并单击表单按钮)
Clicking #39;OK#39; on alert or confirm dialog through jquery/javascript?(在警报上单击“确定或通过 jquery/javascript 确认对话框?)
QunitJS-Tests don#39;t start: PhantomJS timed out, possibly due to a missing QUnit start() call(QunitJS-Tests 不启动:PhantomJS 超时,可能是由于缺少 QUnit start() 调用)