One, the corresponding event
KeyDown: Press any key on the keyboard can be triggered, press the non-release of the repeated trigger
KeyPress: Triggered when a character key on the keyboard is pressed and repeated when pressed
KeyUp: Triggers when the key is released
Event Order: Keydown>keypress>keypup
Capture key events in a text box where you need to be aware:
1.keydown, keypress occurs before the content of the text box changes, KeyUp occurs after the text box changes.
2. If the input is in Chinese, keypress will not trigger
Second, how to get the key value
In JS get keyboard pressed key values are: event.keyCode
, event.charCode
and event.which
.
Google Chrome: yes event.keyCode
, event.charCode
and event.which
are compatible.
Firefox: valid for event.keyCode
some key values, such as the next key (37,38,39,40), enter key (PgUp), PgDn (34) and other parts of the valid, the number key, the letter key is invalid.
event.which
is also part of the key value valid, such as the letter key, number key, enter key, backspace key and so on, on the next key, PgUp (34) key is invalid.
event.charCode
is also valid for some key values, such as the letter key, the number key, backspace key and so on, on the ENTER key, the next key, PgUp (34), the key is invalid.
ie: in, IE8 and the following browsers are not event.charCode和event.which
, event.keyCode
for most of the key values can be obtained, but there are a small number of not get
The wording of compatibility is as follows:
var Code=e.keycode | | E.which | | E.charcode
Iii. What events should be used to get key values
- After the KeyDown is triggered, the keyup is not necessarily triggered, and when the KeyDown is pressed, the mouse is dragged and the KeyUp event is not triggered.
- KeyPress is primarily used to capture numbers (note: symbols including shift+ numbers), letters (note: include capitalization), keypads, etc. except f1-12, SHIFT, Alt, Ctrl, Insert, Home, PgUp, Delete, End, PgDn, ScrollLock, Pause, NumLock, {Menu key}, {Start key}, and ANSI characters outside the arrow key
- KeyDown and KeyUp can usually capture keyboards in addition to prscrn all keys (special keys for special keyboards are not discussed here)
- KeyPress can capture only a single character, KeyDown and KeyUp capture key combinations.
- KeyPress can capture the case of a single character, KeyDown and KeyUp cannot.
- KeyPress does not differentiate between the numeric characters of the keypad and the main keyboard, KeyDown and KeyUp.
Summary: Use KeyPress event object to get key characters, use KeyDown event to get function characters (such as enter,backspace, etc.)
JS Keyboard Related Knowledge Summary