JavaScript onkeydown Event
The onkeydown event is triggered when the user presses a keyboard key. Unlike the onkeypress event, the onkeydown event is a process that responds to any key press (including function keys), and the onkeypress event only responds to the process that comes after the character key press.
hint
Internet Explorer/Chrome browser uses event.keyCode to retrieve the pressed characters, while browsers such as Netscape/Firefox/Opera use event.which.
onkeydown Get the key pressed by the user
The following is an example of using the onkeydown event to obtain information about the user pressing the keyboard key:
The code copy is as follows:
<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, and the commonly used key values correspond to the following:
| Number value | Actual key value |
|---|---|
| 48 to 57 | 0 to 9 |
| 65 to 90 | a to z (A to Z) |
| 112 to 135 | F1 to F24 |
| 8 | BackSpace (Backspace) |
| 9 | Tab |
| 13 | Enter |
| 20 | Caps_Lock (caps lock) |
| 32 | Space (space bar) |
| 37 | Left (left arrow) |
| 38 | Up (up arrow) |
| 39 | Right (right arrow) |
| 40 | Down (down arrow) |
In web applications, you can often see examples of using the event.keyCode/event.which of the onkeydown event to obtain some keyboard operations of the user, thereby running certain applications. If the caps lock key (20) is pressed when the user logs in, it will prompt capital lock; if the user presses the left and right arrows, it will trigger the page turning up and down, etc.
After obtaining the Unicode encoded value, if you need to get the actual corresponding key value, you can obtain it through the fromCharCode method of the Srring object (String.fromCharCode()). Note that the characters are always capitalized, while for some other function keys, the characters obtained may not be easy to read.
PS: Here I recommend an online query tool about JS events, which summarizes the commonly used event types and function functions of JS:
A complete list of javascript events and functions:
http://tools.VeVB.COM/table/javascript_event