First understand the differences between various events
KeyDown: occurs when the key is pressed when the control has focus.
KeyPress: The Key is pressed when the control has focus.
KeyUp: occurs when the key is released when the control has focus.
1. KeyPress is mainly used to receive ANSI characters such as letters and numbers. KeyDown and KeyUP events can usually capture all the buttons except PrScrn (the special keys of the special keyboard are not discussed here
2. KeyPress can only capture a single character. KeyDown and KeyUp can capture a combination of keys.
3. KeyPress does not display the physical status (SHIFT key) of the keyboard, but only transmits one character. KeyPress uses the big and lowercase characters of each character as different key code interpretations, that is, two different characters. KeyDown and KeyUp cannot determine the size of key-value letters. KeyDown and KeyUp use two parameters to explain the upper and lower case formats of each character: keycode-display the physical key (Return A and a as the same key) and shift-indicate the status of shift + key and return one of A or.
5. KeyPress does not distinguish between the numeric characters of the keypad and the keypad. KeyDown and KeyUp distinguish between the numeric characters of the keypad and the keypad.
6. A KeyDown or KeyUp event occurs when a key is pressed or released. Generally, when you press the keyboard key, the keyboard is usually opened immediately (different from the mouse). Therefore, there is little difference between the two events. In addition, up is different from the other two: To determine the status after the key is modified, up must be used.
We can use the keydown event to block user input. For example, an input field can only contain numbers.
KeyCode of the number key on the keyboard
[48-57] Number key
[96-105] keypad
In addition, the Backspace key is allowed to be deleted.
The Code is as follows:
Copy codeThe Code is as follows:
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 ){
// Number
If (keyCode> = 48 & keyCode <= 57) return true
// Keypad
If (keyCode> = 96 & keyCode <= 105) return true
// Backspace key
If (keyCode = 8) return true
Return false
}