当keydown打开警报时,密钥不会触发

编程入门 行业动态 更新时间:2024-10-25 06:30:35
本文介绍了当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/boblauer/jaGwT/ 当keydown打开警报时,不会触发密钥,但是当未打开警报时,会触发密钥。这是来自jsfiddle的代码:

You can see a very simple example here: jsfiddle/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打开警报时,密钥不会触发

本文发布于:2023-11-27 01:37:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1636046.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:密钥   警报   keydown

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!