问题
The javascript keypress
event is deprecated:
https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event
Some people advise to rely exclusively on the keydown
event, eg.:Keydown
is the only keyboard event we need
https://www.mutuallyhuman.com/blog/2018/03/27/keydown-is-the-only-keyboard-event-we-need/
The problem is that keydown
and keypress
are not synonymous. Critically, they do not return the same character in many/most cases. Keydown
represents which key on the keyboard was pressed, while keypress
represents which character the user actually typed.
In English, the distinction is important with regard to case:
letter = String.fromCharCode(event.which);
When pressing the key "a" on the keyboard, letter would be "a" with keypress
, but it is "A" with keydown
.
The situation gets way more complicated with JCK languages because keypress
receives correct characters for international keyboard layouts, unlike keydown
which converts everything to single byte characters.
keydown and keyup events are now fired during IME composition:
https://www.fxsitecompat.com/en-CA/docs/2018/keydown-and-keyup-events-are-now-fired-during-ime-composition/
So, with keypress
being deprecated, what should we use when we care about the character that the user intended to type, taking into account case, non-ASCII characters and multi-byte characters?
Related questions and references:
keyup event always return uppercase letter
=> The answer recommends the use of keypress
.
String.fromCharCode not working on keydown event
=> The answer recommends the use of keypress
.
String.fromCharCode on keypress and keydown are returning wrong characters
=> The answer notes that the keypress
and keydown
events are not interchangeable.
Replacement for deprecated `keypress` DOM event
=> The answer suggests using keydown
without noting the difference it makes in terms of handling letter case, non-ascii characters and multi-byte characters.
Also, the suggested alternative beforeinput
does not appear to have any browser support.
Alternative for Keypress Event in Firefox Version 65+
=> Question summarily downvoted, with a comment suggesting using keydown
or beforeinput
without having addressed any of the pitfalls mentioned above.
来源:https://stackoverflow.com/questions/55861101/keypress-being-deprecated-how-to-get-the-characters-typed-by-a-user