若要讀取使用者的鍵盤輸入通常會聽 Keydown 事件,如:
String.fromCharCode(keydownEvent.keycode)
但這方法會將數字鍵盤的 1 的 keycode 轉成字母 a
其實同一個按鍵的 keydown.keycode 在各瀏覽器的的值極不一致,這篇專文 JavaScript Madness: Keyboard Events 有深入討論。
The keypress events are generally the easiest to work with.
結論就是聽 kepress event,並使用 keypress.which
原因:
On keydown and keyup events, the keycodes are not character codes, and this conversion will give wild results for many keys. There is no general portable way to convert keycodes to characters.
這篇提到 keydown 跟 keypress 當初設計的用意不同。
http://stackoverflow.com/questions/11030532/keypress-and-keyup-why-is-the-keycode-different
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.
這裡有展示各個 event 的 keycode
http://www.w3.org/2002/09/tests/keys.html
留言