防止 JavaScript keydown 事件在按住时被多次处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6087959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:24:28  来源:igfitidea点击:

Prevent JavaScript keydown event from being handled multiple times while held down

javascript

提问by Chris

I have this code:

我有这个代码:

else if (e.keyCode == 32){
      fired = true;

In a keyDown function (I have added the document.addEventListener code). Now it works just fine, and does exactly what I want it to do. But here's the problem: if you hold downthe key, it keeps making fired = true over and over again continuously until it is released. I just want it to set fired = true; once, even if the key is held down.

在 keyDown 函数中(我添加了 document.addEventListener 代码)。现在它工作得很好,并且完全符合我的要求。但问题是:如果你按住这个键,它会一遍又一遍地不断地使 fire = true 直到它被释放。我只是想让它设置 fire = true; 一次,即使按键被按下。

回答by Isti115

If browser compatibility is not your main concern*, you could try accessing the .repeatproperty of the KeyboardEvent, as documented here:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat

如果浏览器兼容性不是您的主要关注点*,您可以尝试访问 的.repeat属性,如下所述KeyboardEventhttps:
//developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat

By doing something like this in your handler function:

通过在你的处理函数中做这样的事情:

function keyDown (e) {
  if (e.repeat) { return }

  // do stuff here
}

you could avoid the repeated keystrokes.

您可以避免重复击键。



*: on the MDN site it states that it works in Firefox, and I have successfully used it in Chrome, so the two major browsers should have no problem with it

*:在MDN网站上说它可以在Firefox中运行,我在Chrome中成功使用过它,所以两大浏览器应该没有问题

回答by mr_eclair

    var fired = false;

    element.onkeydown = function() {

        if(!fired) {
            fired = true;
            // do something
        }
    };

Then Use onkeyup event

然后使用 onkeyup 事件

    element.onkeyup = function() {
     fired = false;
    };

回答by www139

Try this :)

试试这个 :)

You can determine anywhere else in your script if a key is down by simply determining if keydownis true! You can also execute additional script when a key is down by replacing the console.log();with whatever you want to be down when a key is down.

您可以通过简单地确定是否keydown为真来确定脚本中的任何其他地方是否已关闭!您还可以在按键关闭时执行其他脚本,方法是将 替换为console.log();您想要在按键关闭时关闭的任何内容。

Please tell me if this can be improved.

请告诉我这是否可以改进。

var keydown = false;
window.addEventListener('keydown', function() {
  if (!keydown) {
    keydown = true;
    console.log('key down');
  }
  window.addEventListener('keyup', function() {
    keydown = false;
  });
});

回答by Vikram

Another approach to handle this (suggested by my friend):

处理此问题的另一种方法(由我的朋友建议):

  1. Note the timeStamp when everytime the keydown event happens

  2. Calculate the difference between current timeStamp (t2) and the previous timeStamp (t1)

  3. (a) If the difference is less than some predetermined threshold, then it is the second keydown (means we have already executed the code to happen on that event). Hence, we may choose not to execute the code again

    (b) If the difference is greater than the predetermined threshold, then it is the first keydown. Hence, we would execute the code

  1. 请注意每次发生 keydown 事件时的时间戳

  2. 计算当前时间戳(t2)和前一个时间戳(t1)之间的差异

  3. (a) 如果差异小于某个预先确定的阈值,那么它是第二次 keydown(意味着我们已经执行了在该事件上发生的代码)。因此,我们可能会选择不再执行代码

    (b) 如果差值大于预定阈值,则为第一个 keydown。因此,我们将执行代码

回答by alex

Use keyupevent. It is fired when they key is lifted.

使用keyup事件。当他们的钥匙被提起时它会被触发。

回答by 538ROMEO

Solutions above dont take in account multiple key presses (imagine a game where the user can presse up and left at the same time but both need to be triggered just once). I needed a universal solution for disabling key repeat on multiple keyPress for ALL keys:

上面的解决方案不考虑多次按键(想象一个游戏,用户可以同时向上和向左按下,但都只需要触发一次)。我需要一个通用解决方案来禁用所有键的多个 keyPress 上的重复键:

// create an array with 222 (number of keycodes) values set to true
var keyEnabledArray = Array(222).fill(true);

document.onkeydown = function(e){
    // disable the key until key release
    if(keyEnabledArray[e.keyCode]) {
        keyEnabledArray[e.keyCode] = false;
    }
};

document.onkeyup = function(e){
    // enable the specific key on keyup
    keyEnabledArray[e.keyCode] = true;
}; 

Check the snippet below:

检查下面的片段:

// create an array with 222 true values
var keyEnabledArray = Array(222).fill(true);

document.onkeydown = function(e){
    // disable the key until key release
    if(keyEnabledArray[e.keyCode]) {
        keyEnabledArray[e.keyCode] = false;
        document.getElementById('console').innerHTML += e.keyCode + '<br>';
    }
    
};

document.onkeyup = function(e){
    keyEnabledArray[e.keyCode] = true;
};
Press a key:
<div id='console'></div>

回答by ChrisK

To avoid repeated keydownevent, block it after firing and unblock it with keyup. You should avoid variable 'fired' being global, so use code block with ES6+ or closure in older version of JS.

为避免重复keydown事件,在触发后阻止它并使用 解除阻止它keyup。你应该避免变量“fired”是全局的,所以在旧版本的 JS 中使用带有 ES6+ 的代码块或闭包。

For ES6:

对于 ES6:

{ let fired = false;    // code block to exclude 'fired' from global scope
    element.addEventListener('keydown', (e) => {
        // only accept key down when was released
        if(!fired) {
            fired = true;
            // check what key pressed...
            if (e.keyCode === 32) {
                // and do what you need with it
            }
        }
    });

    element.addEventListener('keyup', (e) => {
        fired = false;
    });
}

For older version of JS use IIFE:

对于旧版本的 JS,请使用 IIFE:

(function(){
    let fired = false;
    element.addEventListener('keydown', function(e) {
        // only accept key down when was released
        if(!fired) {
            fired = true;
            // check what key pressed...
            if (e.keyCode === 32) {
                // and do what you need with it
            }
        }
    });

    element.addEventListener('keyup', function(e) {
        fired = false;
    });
})();

回答by theHaymaker

Unlike the solution above from Hungary where you return falseif e.repeatis true, my use case required me to do the following to effectively disable the onChange event on a text input/textarea.

与上面来自匈牙利的解决方案不同,return false如果e.repeat是真的,我的用例要求我执行以下操作以有效禁用文本输入/文本区域上的 onChange 事件。

function keyDown (e) {
  if(e.repeat) {
    e.preventDefault()
  }

  // do stuff here
}

Larger context of my use case (in JSX):

我的用例的更大上下文(在 JSX 中):

<textarea 
  ref={formulaInput}
  defaultValue={formulaDefinition.string}
  onDoubleClick={handleLock} 
  onKeyUp={handleUnlock}
  onKeyDown={(e) => {
    if(e.repeat) {
      e.preventDefault()
    }
  }}
  onKeyPress={(e) => {
    if(e.repeat) {
      e.preventDefault()
    }
  }}
  readOnly={!focusLock}
  onChange={handleChange} 
  className={`formula-input ${focusLock ? 'formula-input__locked' : ''}`}
  id='2'
></textarea>