keypress 和 keyup - 为什么 keyCode 不同?

2022-01-13 00:00:00 keyboard javascript

相关:JavaScript KeyCode vs CharCode

这里有一些代码,您可以在家中或在 jsfiddle 中尝试:

Here is some code you can try at home or in a jsfiddle:

el.addEventListener( 'keyup', function( e ) { 
    console.log( 'Keyup event' );
    console.log( e.keyCode );
} ); 
el.addEventListener( 'keypress', function( e ) { 
    console.log( 'Keypress event' );
    console.log( e.keyCode );
} );

为什么keyCode不一样?

Why is the keyCode different?

我可以理解为什么一个人应该只使用按键,但我不明白的是两个按键事件如何在给定键盘上相同的按键时给出不同的 keyCode.

I can understand why one should use keypress only, but what I don't understand is how two key events, given the same hit key on the keyboard, give different keyCodes.

PS:我不担心旧版浏览器的支持,我在 Chrome 中尝试过,很惊讶,但找不到解释.

PS: I'm not worrying about legacy browsers support, I tried this in Chrome and was surprised, and couldn't find an explanation.

推荐答案

这些事件的目的完全不同.使用 keyupkeydown 识别物理键,使用 keypress 识别键入的字符.两者是具有不同事件的根本不同任务;不要试图将两者混为一谈.特别是,keypress 事件上的 keyCode 通常是多余的,不应使用(旧版 IE 除外,但请参阅下面的链接文档了解更多信息);对于可打印的按键,它通常与 whichcharCode 相同,尽管浏览器之间存在一些差异.

The events are for completely different purposes. Use keyup and keydown for identifying physical keys and keypress for identifying typed characters. The two are fundamentally different tasks with different events; don't try to mix the two. In particular, keyCode on keypress events is usually redundant and shouldn't be used (except in older IE, but see the linked document below for more on that); for printable keypresses it's usually the same as which and charCode, although there is some variation between browsers.

Jan Wolter 关于关键事件的文章,已经在另一个答案中链接到,是权威词对我来说这个主题,并有表格描述了每种不同属性为每种类型的键事件和每种浏览器返回的内容.

Jan Wolter's article on key events, already linked to in another answer, is the definitive word on this subject for me and has tables describing what each of the different properties returns for each type of key event and each browser.

相关文章