The Keydown event prevents the user from entering the implementation code

  • 2020-03-30 02:20:38
  • OfStack

So let's see what the differences are

KeyDown: occurs when a key is pressed while the control has focus
KeyPress: occurs when a key is pressed while the control has focus
KeyUp: occurs when the key is released while the control has focus

1. KeyPress is mainly used to receive ANSI characters such as letters and Numbers. KeyDown and KeyUP event procedures typically capture all keys except PrScrn on the keyboard (special keys for special keyboards are not discussed here)

2. KeyPress can only capture a single character, while KeyDown and KeyUp can capture a key combination.

3. KeyPress does not show the physical state of the keyboard (SHIFT key), but simply passes a character. KeyPress interprets the large and lowercase forms of each character as different key codes, that is, as two different characters. KeyDown and KeyUp cannot determine the size of a key-value letter. KeyDown and KeyUp interpret the uppercase and lowercase forms of each character with two arguments: keycode - which shows the physical keys (returning A and A as the same key) and shift - which indicates the status of the shift + key key and returns either A or A.

5. KeyPress does not distinguish numeric characters of keypad and main keyboard, and KeyDown and KeyUp distinguish numeric characters of keypad and main keyboard.

KeyDown, KeyUp events occur when a key is pressed down or released. Since the key on the keyboard is typically pressed and released immediately (unlike the mouse), there is little difference between which of the two events to use. Also, there is one difference between up and the other two: to determine the state of the key after modification, you must use up.

We can use keydown events to block user input, such as only Numbers for an input field

The keyCode for the number keys on the keyboard

[57] 48 - numeric keys
[96-105] numeric keypad
Also allows Backspace key deletion

The following code
 
var input = document.getElementById('number_ipt') 
input.onkeydown = function(e) { 
var keyCode = e.keyCode 
if ( !isNumber(keyCode) ) return false 
} 

//Only Numbers can be entered
function isNumber(keyCode) { 
//  digital  
if (keyCode >= 48 && keyCode <= 57 ) return true 
//keypad
if (keyCode >= 96 && keyCode <= 105) return true 
//The Backspace key
if (keyCode == 8) return true 
return false 
} 

Related articles: