我正在使用 Ubuntu 10 并在 Firefox 3.6 和 Chrome 5 中尝试以下代码。
$(document).ready(function(){
$(document).bind("keypress", function(e){
alert("Pressed");
});
});
令人惊讶的是,上面的代码在 FF3.6 中运行良好。即每按下一个键,我都会收到一个警报框。
但在 Chrome 中,我看到了不同的行为。例如,当我按上/下翻页、上/下/左/右箭头键时,我没有收到警报框(不幸的是,这些是我迫切想要跟踪的关键事件)。
有人知道为什么 Chrome 没有将“按键”事件绑定(bind)到某些按键,例如向上/向下翻页、向左/向右箭头吗?
最佳答案
onkeypress 事件最初是 Internet Explorer 的专有事件,后来包含在其他浏览器中,但实现不同。 Chrome/Safari 忠实于 Microsoft 实现,为此 the documentation状态:
As of Microsoft Internet Explorer 4.0, the onkeypress event fires and can be canceled for the following keys:
Letters: A - Z (uppercase and lowercase)
Numerals: 0 - 9
Symbols: ! @ # $ % ^ & * ( ) _ - + = < [ ] { } , . / ? \ | ' ` " ~
System: ESC, SPACEBAR, ENTER
对于其他按键,您应该绑定(bind)到 keydown 或 keyup。
Quirksmode.org compatibility reference状态:
When the user presses special keys such as the arrow keys, the browser should NOT fire keypress events.
关于jquery - 使用 JQuery 绑定(bind)按键事件在 Chrome 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3417938/