問題描述
相關(guān):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?
我可以理解為什么一個人應(yīng)該只使用按鍵,但我不明白的是兩個按鍵事件如何在給定鍵盤上相同的按鍵時給出不同的 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.
推薦答案
這些事件的目的完全不同.使用 keyup
和 keydown
識別物理鍵,使用 keypress
識別鍵入的字符.兩者是具有不同事件的根本不同任務(wù);不要試圖將兩者混為一談.特別是,keypress
事件上的 keyCode
通常是多余的,不應(yīng)使用(舊版 IE 除外,但請參閱下面的鏈接文檔了解更多信息);對于可打印的按鍵,它通常與 which
和 charCode
相同,盡管瀏覽器之間存在一些差異.
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 關(guān)于關(guān)鍵事件的文章,已經(jīng)在另一個答案中鏈接到,是權(quán)威詞對我來說這個主題,并有表格描述了每種不同屬性為每種類型的鍵事件和每種瀏覽器返回的內(nèi)容.
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.
這篇關(guān)于keypress 和 keyup - 為什么 keyCode 不同?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!