A key is pressed on the keyboard

  • 2020-03-30 04:09:23
  • OfStack

JavaScript onkeydown event

The onkeydown event is triggered when the user presses a keyboard key. Unlike (link: #) events, the onkeydown event responds to any key pressed (including the function key), while the onkeypress event only responds to the character key pressed.

prompt

Internet Explorer/Chrome USES event.keycode to fetch the pressed characters, while browsers such as Netscape/Firefox/Opera use event.which.

Onkeydown gets the key that the user pressed

The following is an example of using the onkeydown event to get the information of the keypad 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, the event. The keyCode/event which is a key of the corresponding numerical values (Unicode), commonly used keys corresponding to the following:

A numeric value The actual key values
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 (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, often can see the event of using the onkeydown event. The keyCode/event which to get the user's keyboard operation, to run some application examples. When the user logs in, if the caps lock key (20) is pressed, the caps lock will be prompted. When a page is turned, if the user presses the left and right arrows, the page is turned up and down.

After obtaining the Unicode encoding value, if the actual corresponding key value is needed, it can be obtained by the Srting object's fromCharCode method (string.fromcharcode ()). Note that you always get an uppercase character for a character, and for some other function keys, you get a character that may not be easy to read.

  PS: here again for you to recommend an online query tool about JS events, summed up the common JS event types and functions:

Javascript events and function description:

(link: http://tools.jb51.net/table/javascript_event)


Related articles: