jQuery 的“keypress”不适用于 Chrome 中的某些键。如何解决?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3901063/
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
jQuery's 'keypress' doesn't work for some keys in Chrome. How to work around?
提问by DaveDev
I'm trying to implement key-press functionality which will remove a div when the user hits Esc
. This works for Firefox & IE with the following code:
我正在尝试实现按键功能,该功能将在用户点击 时删除 div Esc
。这适用于 Firefox 和 IE,代码如下:
$("body").keypress(function(e) {
alert("any key pressed");
if (e.keyCode == 27) {
alert("escape pressed");
}
});
If I hit any key, the first alert
is displayed, and if I hit Escape, the second alert
is also displayed.
如果我按任意键,alert
则显示第一个键,如果按 Escape,alert
也会显示第二个键。
This doesn't work with Chrome though. The first alert
is always displayed if I hit any of the letter keys, but not when I hit Escape, Tab, Space or any of the numbers.
但这不适用于 Chrome。alert
如果我按任何字母键,第一个总是显示,但当我按 Escape、Tab、Space 或任何数字时不会显示。
Why would this be? Is there any way to get Chrome to respond to these key presses?
为什么会这样?有没有办法让 Chrome 响应这些按键?
回答by SLaks
Try handling keydown
instead.
尝试处理keydown
。
回答by bear
use keydown. keypress doesn't work with ESC in Chrome (not sure about other browsers).
使用keydown。keypress 不适用于 Chrome 中的 ESC(不确定其他浏览器)。
$(newTag).keydown(function(e) { //keypress did not work with ESC;
if (event.which == '13') {
ProfilePage.saveNewTag(search_id, $(newTag).val());
}
else if (window.event.which){
$(newTag).remove();
}
});
回答by Dylan Foregger
For ESC key:
对于 ESC 键:
$(document).keydown(function(e) {
if(e.keyCode == 27) { /* Run code */ }
}
For letter keys, like 'L':
对于字母键,如“L”:
$(document).keypress(function(e) {
if(e.which == 108) { }
});
Works in both Chrome and Firefox
适用于 Chrome 和 Firefox
回答by ppolyzos
After the second alert add also
在第二个警报之后也添加
e.preventDefault();
This will prevent the default action of the event to be triggered.
这将阻止触发事件的默认操作。
More info about this method here
关于此方法的更多信息在这里
Your code should look like
你的代码应该看起来像
$("body").keypress(function(e) {
alert("any key pressed");
if (e.keyCode == 27) {
alert("escape pressed");
e.preventDefault();
}});
回答by Gayan Weerakutti
keypress 'ESC'
按键'ESC'
e.which: 0
e.keyCode: 27
keyup 'ESC'
键盘'ESC'
e.which: 27
e.keyCode: 27
For non-printable characters better use keyup
.
对于不可打印的字符,最好使用keyup
.
回答by ghodasara keval
Using Jquery.hotkey js file you can Make Sortcut key
使用 Jquery.hotkey js 文件,您可以制作 Sortcut 键
$(document).bind('keydown', 'esc', function(){ });