当keydown打开警报时,密钥不会触发 [英] Keyup not firing when keydown opens an alert

查看:93
本文介绍了当keydown打开警报时,密钥不会触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个事件处理程序,一个用于keydown,另一个用于keyup。 keydown事件处理程序触发警报消息,但这会阻止keyup事件触发。

I have two event handlers, one for keydown and one for keyup. The keydown event handler triggers an alert message, but this prevents the keyup event from firing.

您可以在此处看到一个非常简单的示例: http: //jsfiddle.net/boblauer/jaGwT/ 当keydown打开警报时,不会触发密钥,但是当未打开警报时,会触发密钥。这是来自jsfiddle的代码:

You can see a very simple example here: http://jsfiddle.net/boblauer/jaGwT/ When the keydown opens an alert, the keyup is not fired, but when an alert is not opened, the keyup is fired. Here's the code from the jsfiddle:

var i = 0;
window.addEventListener('keydown', function(e) {
    if (i++ % 2) alert('down');
    console.log('down');
});

window.addEventListener('keyup', function(e) {
    alert('up');
    console.log('up');
});

我有一个支持收听多个组合键的库(例如'd + f'),因此,当按下某个键时,我需要将其添加到当前按下的键列表中,并且当释放键时,我需要将其从所述列表中删除。我正在遇到的问题是,如果我想要同时按下d + f时显示警报,我从当前按下列表中删除这些键的代码永远不会触发,因为我的密钥处理程序永远不会被调用。

I have a library that supports listening to multiple key combinations (such as 'd + f'), so when a key is pressed, I need to add it to a list of keys that are currently pressed, and when a key is released, I need to remove it from said list. The problem I'm running to is, if I want an alert to show when d + f are pressed at the same time, my code to remove those keys from the 'currently pressed' list never fires, because my keyup handler is never called.

我想不出这个问题的好方法。任何想法?

I can't think of a good work around to this problem. Any ideas?

推荐答案

警报可防止事件发生。你可以做的是手动触发这个功能,因为它无论如何都会发生。

The alert prevents the event from happening. What you could do instead is trigger this function manually, because it happens anyways.

var keyupfunction = function(e){
    alert('up');
    console.log('up');
}

window.addEventListener('keyup', keyupfunction);

window.addEventListener('keydown', function(e) {
    if (i++ % 2) alert('down');
    console.log('down');
    keyupfunction(e);
});

但实际上,你不应该使用警报。它会阻止这些事件,但谁知道它可能会破坏什么。请使用自定义内容。

But really, you shouldn't be using alerts. It prevents these events, but who knows what else it might break. Use something custom instead.

这篇关于当keydown打开警报时,密钥不会触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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