This is the 26th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
Note: In keyboard events, the event event type is KeyboardEvent.
Keydown, KeyPress, and KeyUp keypress events (type)
Js keyboard events are classified into three types: keyDown, KeyPress, and keyUp, all of which inherit the KeyboardEvent interface.
keydown
: Triggered when the keyboard is pressed.keypress
: Triggered when a valued key is pressed, that is, Ctrl, Alt, Shift, Meta, etc., this event will not be triggered. For keys that have values, they fire first when pressedkeydown
Event, and thenkeypress
Events.keyup
: Triggered when the keyboard is released.
The sequence of events for pressing a release key is:
- keydown
- keypress
- keyup
Long press not loose keyboard event sequence is:
- keydown
- keypress
- keydown
- keypress
- . (repeat)
- keyup
KeyboardEvent. Repeat Is used to determine whether a key is being held
KeyboardEvent. Repeat returns a Boolean value indicating whether the key is being held.
If a key is pressed and does not release, the browser continues to fire keyDown and KeyPress events until release. From this can judge the long press does not release the special treatment, whether to repeat the key and so on.
The use of event.key is recommended (E.keycode and E.White have been abandoned and are not recommended)
KeyCode and Which are not recommended, but almost all browsers maintain compatibility support! It can be used at ease.
Event.key indicates which character is pressed (case sensitive)
Event. key can accurately represent the character being pressed, but cannot represent the exact physical key, such as the number key on the upper part of the keyboard or the number keypad. Event. key can obtain the corresponding number character.
Event. key is case sensitive for letters, so be careful when judging. For example, output test console.log(“key: “+event.key);
About E. keycode and E. White
E. keycode and E. White represent the numeric value of a keyboard key and are common attributes used to determine which key to press.
Below are MDN recommendations for e. Keycode and E. White after they have been abandoned. See MDN KeyboardEvent for more information.
deprecated
One of the biggest problems with using E. keycode and E. white is the inability to be case-sensitive. Because the keyCode is the same for both uppercase and lowercase letters. Of course, there are other problems, see the introduction below.
Why not use keyCode?
The reason why keyCode and which are not recommended is that they are inconvenient to use in practice. Because keyCode corresponds to specific physical key numeric values, it is impossible to distinguish what characters are represented.
Here are a few keyCode questions in more detail:
- Different characters share a keyCode value
KeyCode corresponds to physical keys, such as <, >., and the numeric key 1 on the keyboard. , 2@, 3#, 4$, etc., are multiple characters on the same key, the corresponding keyCode will be repeated.
Check the difference between keyCode and key using the keyDown event as follows.
window.addEventListener("keydown".function (e) {
console.log(` keyCode:${e.keyCode}- the key:${e.key}`);
})
Copy the code
Different characters have the same keyCode. You need to combine the Shift key to determine which character to press.
The same is true of the case of letters.
- The same keyCode may differ
This happens with the small number keys in the full keyboard. The same key, shift hold down, the keyCode is different.
While the top letter case, the top number keys, etc., hold down shift, the same key keyCode is unchanged.
- The same character keyCode may differ
As in the example above, the 8 in the small number key also corresponds to the ArrowUp arrow under the Shift key. Its keyCode is 38. And the standard up arrow, keyCode is also 38.
That is, if the characters are the same, the keyCode should be the same. However, if you test the + and – keys on the numeric keypad, and the add and subtract keys on the right of the numeric keys at the top of the keyboard, the keyCode values will be different.
That is, the same character may have a different keyCode.
This part mainly refers to Zhang Xinxu’s farewell JS keyCode
Event listening use of the composite keykeydown
ctrl
,shift
The event listener for the combination key is usually used when the combination key is combined with other keyskeydown
The event,keypress
和 keyup
We’re not listening.
For example, listen to the print shortcut key CTRL + P and prevent the printing interface from opening:
Using event.code:
Event. code is recommended for letter keys and Event. key is recommended for other character keys.
window.addEventListener("keydown".function (e) {
if(e.ctrlKey && e.code=="KeyP"){ e.preventDefault(); }});Copy the code
If you want to use the event. The key judgment, may need to judge the case: the if (e.c. with our fabrication: trlKey && (e.k ey = = “p” | | e.k ey = = “p”)).
Common control key judgment, such as Enter, Ctrl, do not need to judge the case, and more convenient to use.
For example, determine the Enter key:
window.addEventListener("keydown".function (e) {
if(e.key=="Enter") {console.log("Enter!"); }});Copy the code
event.key
Compatibility support starts with IE9, whileevent.code
It is not supported in the entire IE family, which is probably why MDN recommends using key instead of keyCode or which.
Using event.keyCode:
If event.key (such as below Internet Explorer 9) or Event. code (not supported by the entire ie family) is not supported, you can go back to using Event. keyCode or Event. which, since browsers currently support all of them.
window.addEventListener("keydown".function (e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if(e.ctrlKey && keyCode==80){ e.preventDefault(); }});Copy the code
About the normal use of Event.keyCode
Take the above example:
The keycode for the CTRL key is 17. CtrlKey, but generally browsers that support ctrlKeys also support Event. key, and even Event. code. Therefore, since ctrlKey is used, you can also use Event. key.
Regardless of IE support, event.code can even be used.
But the event. The keyCode/event. Which due to the compatibility, basic all browsers support, therefore, under normal circumstances, or use the event. The keyCode.
KeyboardEvent. GetModifierState keyArg () method returns the special state of the modifier keys
GetModifierState () is used to return the status of the modifier key, or true if pressed. It is generally used for more complex modification key judgments.
Examples include “AltGraph”(Alt and Ctrl), “ScrollLock”, and “Fn”(Function, but it’s only supported on Android and seems to have limited functionality).
Since getModifierState() has limited support on many systems, it may be better to log and determine key press and release with code. These will be covered in the next article.
See MDN for an introduction to getModifierState
Use Event.code to determine the exact physical keys
Event. code returns the code of the physical key corresponding to the event as a string. It accurately identifies unused physical keys, something the key attribute cannot do.
For example, for the left and right Alt keys, event.key returns Alt, and for the number keys on the keypad and the number keys on the top of the keyboard, event.key returns the same value.
But Event.code is differentiated.
Here is an example test that outputs code and key:
window.addEventListener("keydown".function (e) {
console.log(` code:${e.code}- the key:${e.key}`);
});
Copy the code
Especially above, the distinction between AltLeft and AltRight.
Special function keys altKey, ctrlKey, metaKey, shiftKey (modify key combination function key judgment)
These special keys, which can be obtained directly from the event. Property, are read-only bool values indicating whether or not a key was pressed.
KeyboardEvent.altKey
: Indicates whether to pressAlt
或Option
或⌥
The key.KeyboardEvent.ctrlKey
: Indicates whether to pressCtrl
The key.KeyboardEvent.metaKey
: Indicates whether to press⊞
或⌘ Command
The key.KeyboardEvent.shiftKey
: Indicates whether to pressShift
The key.
These special keys, also called modifier keys, are used to modify the default behavior of other keys. Perform different operations by combining one modifier key with another.
Often used to determine combination keys.
For example, whether to press copy (CTRL + C) :
window.addEventListener("keydown", function (e) {
if(e.ctrlKey && e.code=="KeyC"){
console.log("执行了 ctrl+c 复制"); }});Copy the code
KeyCode and 44PrntScrn
Keyup event listening is required
KeyCode 44 represents the screen capture key, Prt Sc SysRq/PrntScrn is generally located on the upper right side of the keyboard and F12 on the right side (there are differences between different keyboards).
It is a system screenshot shortcut used to capture the entire screen to the “Clipboard”, press the screenshot, paste directly to a location.
PrntScrn key listening requires the keyup event. Other events keyPress and keyDown cannot be monitored.
This also means that PrntScrn keystroke events cannot be blocked.
window.addEventListener("keyup".function (e) {
var keyCode = e.keyCode ? e.keyCode : e.which;
if (keyCode == 44) {
console.log(` code:${e.code}- the key:${e.key}`);
console.log("PrntScrn key lift");
// e.preventDefault(); There is no way to block screenshots}});Copy the code
Output:
Code: PrintScreen -- key: PrintScreen PrntScrn The key is liftedCopy the code
About the key and keyCode problem under Chinese input method when the input box cursor is pressed
If, the cursor is in the input box and the Chinese input method is used at the same time, the keyCode of the key is always 229 and the key is always Process.
Of course, except for typing, the other keys are correctly recognized:
Refer to the recommended
- reference
MDN KeyboardEvent and other MDN related information
- Query key Code website recommendations
A recommended site to query the key, code, and which values for keys is keycode.info/.
- A site of keyboard event properties and status
This is a more detailed demo of the current key properties and state of the small game, showing the current key events, event properties and modifier keys.
Js-keyevents -demo.vercel.app/ and github github.com/atapas/js-k…
Of course, in the actual development, you can directly check the test output, convenient and simple.