This article describes the method of Javascript controlling the input time format. Share it for your reference. The specific analysis is as follows:
I used to make a Javascript input to control the time format, mainly using the keydown and keyup events, but I felt that the writing was very complicated and there were bugs.
Today I learned about the difference between keypress events and keydown and keyup. It's roughly as follows (just know so much at the moment):
keydown: Triggered when the key is pressed. Through event, you can get the keyCode and get the value before input into the text box;
keyup: triggered when the key is popped up (release). The keyCode can be obtained through event and the value after input from the text box can be obtained;
keypress: This event is basically the same in Chrome and IE, but Firefox is a bit different;
1. In Chrome and IE: As long as the key pressed can appear characters in the text box, it will be triggered (such as input letters, numbers, symbols, etc.), the keyCode can be obtained through event, and the event.key is undefined; if the characters cannot appear, it will not be triggered (such as arrow keys, Home, Backspace, etc.)
2. In Firefox: keys such as letters, numbers, symbols, directions, backspaces, etc. can all trigger. The key name can be obtained through event.key. If the key pressed can output characters, event.keyCode is 0. If the character cannot be output, event.keyCode is the corresponding ASCII code.
Going back to the topic, look at the code first (the event mentioned above is equivalent to the e in the following code):
The code copy is as follows: var isFF = /firefox/i.test(navigator.userAgent);
$("input").on({
keyup : function (e) {
!/^[/d:]+$/.test(e.target.value) && (e.target.value = "");
},
keypress : function (e) {
if (isFF && e.keyCode !== 0) {
/// Pressing any key in Firefox will trigger the keypress event, while in IE/Chrome will only trigger the key that can output characters
/// For Firefox, e.keyCode!==0 presses one of the backspace, direction, Home and other keys.
} else {
if (e.target.value.length > 7)
return false;
if (//d{2}$/.test(e.target.value)) {
e.target.value += ':';
}
var char = String.fromCharCode(e.keyCode === 0 ? e.which : e.keyCode);
if (!/^/d/.test(char))
return false;
}
}
});
IsFF && e.keyCode !== 0 is used to distinguish between keys that can output characters in Firefox and keys that cannot output characters. Since e.keyCode in Firefox may not necessarily obtain the value, e.which is used instead.
Keyup is used to deal with the problem of being able to enter Chinese or letters when using the input method.
Use String.fromCharCode() to get the characters corresponding to the ASCII code.
I hope this article will be helpful to everyone's JavaScript programming.