How can I avoid autorepeated keydown events in JavaScript?

后端 未结 4 1633
离开以前
离开以前 2020-12-01 07:59

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 co

4条回答
  •  情话喂你
    2020-12-01 08:32

    Another simple adjustment to the accepted answer to allow for the multiple keys scenario:

    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 = {};
    });
    

提交回复
热议问题