javascript 按下删除键时无法触发按键事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10187431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:58:00  来源:igfitidea点击:

can't fire keypress event when press delete key

javascriptjavascript-eventskeyevent

提问by qiu8310

I'm finding that the delete key doesn't fire the keypressevent in Chrome, while other keys work. The problem doesn't occur in Firefox, just in chrome, why? Here is my code:

我发现删除键不会keypress在 Chrome 中触发事件,而其他键可以工作。这个问题在 Firefox 中没有发生,只是在 chrome 中,为什么?这是我的代码:

document.addEventListener('keypress', function (e) {
     console.log(e);
}, false);

回答by Josh Davenport

Use keydownor keyupinstead, it captures the delete key (as well as others that keypress doesn't, see http://www.quirksmode.org/js/keys.html)

使用keydownkeyup代替,它捕获删除键(以及其他按键没有的键,请参阅http://www.quirksmode.org/js/keys.html

document.addEventListener('keydown', function (e) {
     console.log(e);
}, false);

回答by BrainCoder

keypressevent for (Del, End, Home,etc..) is not fired in IE, Chrome and safari.. it only works in firefox..

keypress(Del、End、Home 等)的事件在IE、Chrome 和 safari 中不会触发 。它只在Firefox 中有效。.

so you can use the keyupor keydownevent because the keypressevent is intented for real (printable) characters. "keydown"is handled at a lower level so it will capture all non-printing keys like DEL, End, etc

因此您可以使用keyuporkeydown事件,因为该keypress事件旨在用于真实(可打印)字符。"keydown"在较低级别处理,因此它将捕获所有非打印键,如 DEL、End 等