如何避免 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 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何避免 JavaScript 中自动重复的 keydown 事件?

基础教程推荐