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

ε祈祈猫儿з 提交于 2019-12-17 19:33:37

问题


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

$(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

Thanks for the help!


回答1:


Change keypress to keydown:

$(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.

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.




回答2:


Found the answer here: 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."

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.




回答3:


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



来源:https://stackoverflow.com/questions/6311290/keypress-event-not-working-in-ie-and-chrome-but-working-in-ff

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!