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

age*_*eto 26 javascript keyboard jquery

如果用户按下该键,则会触发多个keydown事件.出于可用性原因,我需要使用keydown,而不是keyup,但我想避免这种情况.我的相关代码如下:

$(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;
        }     
      });
Run Code Online (Sandbox Code Playgroud)

因此,当用户按下向下键时,goDown()会被多次触发.即使用户按住键,我也希望它只触发一次.

4es*_*n0k 42

使用event.repeat检测事件是否正在重复.然后,您可以在允许处理程序第二次执行之前等待"keyup".

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;
});
Run Code Online (Sandbox Code Playgroud)

  • 就我而言,测试是“ event.originalEvent.repeat”,但它运行良好。使用jQuery版本1.8.3 (3认同)
  • @agente_secreto如果我按下2个按钮然后只释放其中一个怎么办?然后,已经按下的按钮的事件将被触发,这是不正确的. (2认同)
  • 我真的不明白“allowed”变量的必要性。如果你希望事件只发生一次,你可以在函数的开头使用“if (event.repeat) return;”。[演示](https://jsfiddle.net/SamyBencherif/3j679pzd/14/) (2认同)

mat*_*rad 7

对允许多键情况的已接受答案的另一个简单调整:

var keyAllowed = {};

$(document).keydown(function(e) {
  if (keyAllowed [e.which] === false) return;
  keyAllowed [e.which] = false;
  // code to be executed goes here
});

$(document).keyup(function(e) { 
  keyAllowed [e.which] = true;
});

$(document).focus(function(e) { 
  keyAllowed = {};
});
Run Code Online (Sandbox Code Playgroud)


Gia*_*ley 6

这很简单

$(document).keydown(function(e) {
    if (e.repeat) return;
    // ...
});
Run Code Online (Sandbox Code Playgroud)