Use JS to listen for keyboard press events

Event description

We print out all the properties and methods of the event after the keyboard is pressed (here, press 1 as an example)

			document.onkeydown = function(event){
				console.log(event);
			}

 There are a few properties to note here

key: the name of the pressed key

keyCode : The key code of the key pressed

altKey, ctrlKey, shiftKey: When the combination is pressed (such as ctrl+c), ctrlKey will become true

1. View all keys

(Get the name of the key pressed by event.key) (Get the key code pressed by event.keyCode)

			document.onkeydown = function(event){
				console.log("按下:"+event.key+"键:"+event.keyCode);
			}

The effect after pressing any key:

2. Monitor the Enter press event

Here we take the Enter key (the key code is 13) as an example. If you need to monitor different keys, you can modify the key code.

			document.onkeydown = function(event){
				if(event.keyCode==13){
					// 事件
					console.log("按下了回车键")
				}
			}

3. Monitor key combination

Here is an example of CTRL+A

altKey: true when the Alt+* key combination is pressed

ctrlKey: true when the Ctrl+* key combination is pressed

shiftKey: true when the Shift+* key combination is pressed

			document.onkeydown = function(event){
				if(event.ctrlKey & event.keyCode == 65){
					console.log("按下了CTRL+A")
				}
			}

4. Detailed list of key code values

Key code values ​​for alpha and numeric keys
button key code button key code
A 65 J 74
B 66 K 75
C 67 L 76
D 68 M 77
E 69 N 78
F 70 O 79
G 71 P 80
H 72 Q 81
I 73 R 82
Key code values ​​for alpha and numeric keys
button key code button key code
S 83 1 49
T 84 2 50
U 85 3 51
V 86 4 52
W 87 5 53
X 88 6 54
Y 89 7 55
Z 90 8 56
0 48 9 57
Key code value for a key on the numeric keypad
button key code button key code
0 96 8 104
1 97 9 105
2 98 * 106
3 99 + 107
4 100 Enter 108
5 101 - 109
6 102 . 110
7 103 / 111
Function key key code value
button key code button key code
F1 112 F7 118
F2 113 F8 119
F3 114 F9 120
F4 115 F10 121
F5 116 F11 122
F6 117 F12 123
Control key key code value
button key code button key code
BackSpace 8 Esc 27
Tab 9 Spacebar 32
Clear 12 Page Up 33
Enter 13 Page Down 34
Shift 16 End 35
Control 17 Home 36
Alt 18 Left Arrow 37
Cape Lock 20 Up Arrow 38
控制键键码值
按键 键码 按键 键码
Right Arrow 39 -_ 189
Dw Arrow 40 .> 190
Insert 45 /? 191
Delete 46 `~ 192
Num Lock 144 [{ 219
;: 186 \| 220
=+ 187 ]} 221
,< 188 '" 222
多媒体键码值
按键 键码 按键 键码
音量加 175
音量减 174
停止 179
静音 173
浏览器 172
邮件 180
搜索 170
收藏 171

Guess you like

Origin blog.csdn.net/qq_59636442/article/details/124000853