简体   繁体   中英

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. 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. 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)

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.

If you trigger the alert on keyup instead, this wont be an issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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