Home >Web Front-end >JS Tutorial >JavaScript onkeydown event entry example (a key on the keyboard is pressed)
This article mainly introduces the introductory example of JavaScript onkeydown event. The onkeydown event captures the situation when a certain key on the keyboard is pressed. Friends in need can refer to it.
JavaScript onkeydown event
The onkeydown event is triggered when the user presses a keyboard key. Different from the onkeypress event, the onkeydown event responds to the processing of pressing any key (including function keys), while the onkeypress event only responds to the processing of character keys being pressed.
Tips
Internet Explorer/Chrome browsers use event.keyCode to retrieve the pressed character, while browsers such as Netscape/Firefox/Opera use event.which .
onkeydown gets the key pressed by the user
The following is an example of using the onkeydown event to obtain the information of the keyboard keys pressed by the user:
<html> <body> <script type="text/javascript"> function noNumbers(e) { var keynum; var keychar; keynum = window.event ? e.keyCode : e.which; keychar = String.fromCharCode(keynum); alert(keynum+':'+keychar); } </script> <input type="text" onkeydown="return noNumbers(event)" /> </body> </html>
As shown in the above example, event.keyCode/event.which gets the numeric value (Unicode encoding) corresponding to a key. Common key values correspond to the following:
数字值 | 实际键值 |
---|---|
48到57 | 0到9 |
65到90 | a到z(A到Z) |
112到135 | F1到F24 |
8 | BackSpace(退格) |
9 | Tab |
13 | Enter(回车) |
20 | Caps_Lock(大写锁定) |
32 | Space(空格键) |
37 | Left(左箭头) |
38 | Up(上箭头) |
39 | Right(右箭头) |
40 | Down(下箭头) |
In web applications, you can often see Let’s use event.keyCode/event.which of the onkeydown event to obtain some of the user’s keyboard operations to run some application examples. For example, when the user logs in, if the caps lock key (20) is pressed, the caps lock will be prompted; when there is page turning, if the user presses the left and right arrows, page turning up and down, etc. will be triggered.
After obtaining the Unicode encoding value, if you need to get the actual corresponding key value, you can obtain it through the fromCharCode method (String.fromCharCode()) of the Srting object. Note that for characters you always get uppercase characters, and for some other function keys you get characters that may not be easy to read.
PS: Here we recommend an online query tool about JS events, which summarizes the commonly used event types and functions of JS
The above is the entire content of this chapter. For more related tutorials, please visit JavaScript Video Tutorial!