Let's first understand the differences between each event
KeyDown: Occurs when the key is pressed when the control has focus
KeyPress: Occurs when 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. The KeyDown and KeyUP event processes can usually capture all keys on the keyboard except PrScrn (special keys for special keyboards are not discussed here.
2. KeyPress can only capture a single character, while KeyDown and KeyUp can capture a combination of keys.
3. KeyPress does not display the physical state of the keyboard (SHIFT key), but only passes a character. KeyPress interprets the upper and lower case forms of each character as different key codes, that is, as two different characters. KeyDown and KeyUp cannot determine the size of key-value letters. KeyDown and KeyUp interpret the uppercase and lowercase form of each character with two parameters: keycode - displays the physical key (returns A and a as the same key) and shift - indicates the status of the shift + key and returns A or a One of them.
5. KeyPress does not distinguish between numeric characters of the keypad and the primary keyboard, while KeyDown and KeyUp distinguish between numeric characters of the keypad and the primary keyboard.
6. The KeyDown and KeyUp events occur when (KeyDown) or release (KeyUp) a key. Since the keyboard keys are usually pushed away immediately (this is different from the mouse), there is not much difference between which of these two events. Moreover, there is another difference between up and the other two: to judge the modified state of the key, up must be used.
We can use the keydown event to block user input, for example, a certain input field can only enter numbers
KeyCode of the numeric keys on the keyboard
[48-57] Number keys
[96-105] numeric keypad
Also allow Backspace key deletion
The code is as follows
The code copy 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
// Small numeric keyboard
if (keyCode >= 96 && keyCode <= 105) return true
// Backspace key
if (keyCode == 8) return true
return false
}