简体   繁体   English

Javascript的某些警报会自动关闭?

[英]Certain alerts from Javascript are automatically closing?

I was going to implement response to keys, so I started off with: 我打算实现对按键的响应,所以我开始使用:

window.addEventListener('keydown', function(e) {
    alert(e.keyCode)
}, true)

It works with most keys. 它适用于大多数键。 When I press a key it alerts the key code. 当我按一个键时,它会提示键代码。 (Of course, this is not the final design; just a test to see if it would work to make debugging easier.) (当然,这不是最终的设计;只是一个测试,看它是否可以使调试更容易。)

However, I found some interesting behavior. 但是,我发现了一些有趣的行为。 It does odd things when I use the space key. 当我使用空格键时,它做的事情很奇怪。

When I press the space key, the alert with the number '32' (keycode of space) appears. 当我按空格键时,会出现数字为“ 32”(空格键)的警报。 However, when I release the key, the alert automatically closes! 但是,当我释放钥匙时,警报会自动关闭!

I have found that with the Enter key, I have to press it again to close the alert. 我发现使用Enter键,必须再次按一下以关闭警报。 Not with space though. 虽然没有空间。

Why is this? 为什么是这样?

Because space bar is used by the browser for closing alert messages (like enter). 因为浏览器使用空格键来关闭警报消息(例如回车)。

explanation : The interesting behavior is that the browser use the space bar keyup to closing alerts, so you will see only the dialog beetween your keydown / keyup (in a case of the example when the space bar is not repeated) 说明:有趣的行为是浏览器使用空格键来关闭警报,因此您只会看到在keydown / keyup之间的对话框(在本示例中不重复空格键的情况下)

You are triggering the alert on keydown, which means the keyup event, which the button of the alert probably listens to, happens when the alert is already there, effectively removing the alert immediately. 您将在按下keydown时触发警报,这意味着当警报已经存在时,警报按钮可能会侦听的keyup事件就会发生,从而立即有效地删除警报。

If you trigger the alert on keyup instead, this wont be an issue. 如果改为在启动键盘时触发警报,则不会有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM