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

2022-01-13 00:00:00 keyboard jquery javascript

如果用户按住键,则会触发多个 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;
});

相关文章