keydown事件在按下时被多次处理

keydown事件在按下时被多次处理

本文介绍了防止JavaScript keydown事件在按下时被多次处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

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

在keyDown函数中(我添加了document.addEventListener代码)。现在它工作正常,并完全按照我的要求去做。但问题出在这里:如果你按住键,它会一直反复地持续激活= true,直到它被释放。我只想要它设置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 down the 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.

推荐答案

    var fired = false;

    element.onkeydown = function() {

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





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

这篇关于防止JavaScript keydown事件在按下时被多次处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 22:46