Javascript onkeydown事件只开一次? [英] Javascript onkeydown event fire only once?

查看:112
本文介绍了Javascript onkeydown事件只开一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Heylo家伙,

我希望onkeydown事件只触发一次函数。要再次触发该功能,用户必须释放该键并再次按下/按住。
我知道它相当简单,但我是JS的新手。此外,我更喜欢避免使用jquery或其他库。
还有一件事,这应该适用于ie和firefox。

i want to have a onkeydown event fire a function only once. for that function to fire again, the user has to release the key and press/hold again. I know its fairly simple but im new at JS. Also i prefer to avoid using jquery or other libs. one more thing, this should work for both ie and firefox.

非常感谢!

推荐答案

你可以设置一个标志:

var fired = false;

element.onkeydown = function() {
    if(!fired) {
        fired = true;
        // do something
    }
};

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

或取消绑定并重新绑定事件处理程序(可能更好):

Or unbind and rebind the event handler (might be better):

function keyHandler() {
     this.onkeydown = null;
     // do something
}

element.onkeydown = keyHandler;

element.onkeyup = function() {
    this.onkeydown = keyHandler;
};

有关传统事件处理的更多信息。

您可能还想使用 addEventListener attachEvent 绑定事件处理程序。有关详细信息,请查看 quirksmode.org - 高级事件注册模型

You might also want to use addEventListener and attachEvent to bind the event handlers. For more information about that, have a look at quirksmode.org - Advanced event registration models.

这篇关于Javascript onkeydown事件只开一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆