jQuery 按键事件在 IE 和 Chrome 中不起作用,但在 FF 中起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6311290/
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-08-26 20:40:53  来源:igfitidea点击:

keypress event not working in IE and Chrome but working in FF

jqueryinternet-explorerfirefoxgoogle-chromekeypress

提问by hellomello

Any idea why this might happen? I would usually think that Chrome would be more forgiving with the codes?

知道为什么会发生这种情况吗?我通常会认为 Chrome 对代码更宽容?

$(document).keypress(function(e) {
    if(e.keyCode == 39) rightImage();
    if(e.keyCode == 37) leftImage();
});

Thats what my keypress key looks like. Am I missing something? rightImage(); and leftImage(); are functions which should be working becase I'm using those functions somewhere else too

这就是我的按键的样子。我错过了什么吗?右图();和 leftImage(); 是应该工作的函数,因为我也在其他地方使用这些函数

Thanks for the help!

谢谢您的帮助!

回答by jao

Change keypressto keydown:

更改keypresskeydown

$(document).keydown(function(e) {
    if(e.keyCode == 39) rightImage();
    if(e.keyCode == 37) leftImage();
});

The keydown event occurs when the key is pressed, followed immediately by the keypress event. Then the keyup event is generated when the key is released.

keydown 事件在按键被按下时发生,紧接着是 keypress 事件。然后在松开按键时产生keyup事件。

In order to understand the difference between keydown and keypress, it is useful to understand the difference between a "character" and a "key". A "key" is a physical button on the computer's keyboard while a "character" is a symbol typed by pressing a button. In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. The implementation of the theory is not same in all browsers.

为了理解 keydown 和 keypress 之间的区别,了解“字符”和“键”之间的区别很有用。“键”是计算机键盘上的物理按钮,而“字符”是按按钮键入的符号。理论上,keydown 和 keyup 事件表示按键被按下或释放,而 keypress 事件表示正在输入一个字符。该理论的实现在所有浏览器中并不相同。

回答by AR.

Found the answer here: http://api.jquery.com/keypress/

在这里找到答案:http: //api.jquery.com/keypress/

"If you want to use arrows, delete, backspace keys in Chrome you must use keydown. keypress on these keys work only in Firefox and Opera."

“如果你想在 Chrome 中使用箭头、删除、退格键,你必须使用 keydown。这些键上的按键仅在 Firefox 和 Opera 中有效。”

Your code didn't work for me in iE8 (worked in FF), so I switched keypress to keydown. Works in IE now. Don't have Chrome here to test.

你的代码在 iE8 中对我不起作用(在 FF 中工作),所以我将 keypress 切换为 keydown。现在在 IE 中工作。这里没有 Chrome 来测试。

回答by Vivek Singh

yes this can be achieved by changing onkeypressevent to onkeydown. Moreover this issue exists just in case of Internet Explorer when you want to trigger an event on space click.

是的,这可以通过将onkeypressevent更改为onkeydown. 此外,当您想在空间点击时触发事件时,此问题仅存在于 Internet Explorer 的情况下。