Javascript controls the input time format.
This article describes how Javascript controls the input time format. Share it with you for your reference. The specific analysis is as follows:
Previously, I made a Javascript-controlled time format input, mainly using the keydown and keyup events, but I feel that writing is complicated and there are bugs.
Today I learned about the differences between keypress events and keydown events and keyup events. It is roughly as follows (currently only know so much ):
Keydown:The key is triggered when the key is pressed. You can get the keyCode through event and the value before the text box is input;
Keyup:Triggered when the button is popped up (released). The keyCode can be obtained through event, and the value after the input in 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 pressed key can contain characters in the text box, it will be triggered (such as entering letters, numbers, symbols, etc.), and the keyCode and event can be obtained through the event. the key is undefined. If no character is displayed, it will not be triggered (such as the direction key, Home, Backspace, etc)
2. In Firefox, letters, numbers, symbols, directions, backspace, and other buttons can all be triggered by event. key to obtain the key name. If the key pressed can output characters, the event is returned. the keyCode is 0. If no character is output, event. the keyCode is the corresponding ASCII code.
Go back to the question and look at the Code directly (the event mentioned above is equivalent to e in the code below ):
Copy codeThe Code is as follows: var isFF =/firefox/I. test (navigator. userAgent );
$ ("Input"). on ({
Keyup: function (e ){
! /^ [\ D:] + $/.test(e.tar get. value) & (e.tar get. value = "");
},
Keypress: function (e ){
If (isFF & e. keyCode! = 0 ){
/// Pressing any key in Firefox triggers the keypress event, while in IE/Chrome, only the key that can output characters is triggered.
/// For Firefox, e. keyCode! = 0, one of the buttons is pressed, such as the backspace, direction, and Home.
} Else {
If (e.tar get. value. length> 7)
Return false;
If (/\ d {2} $/.test(e.tar get. value )){
E.tar get. value + = ':';
}
Var char = String. fromCharCode (e. keyCode = 0? E. which: e. keyCode );
If (! /^ \ D/. test (char ))
Return false;
}
}
});
Use isFF & e. keyCode! = 0 is used to distinguish between keys that can output characters in Firefox and keys that cannot output characters. Because e. keyCode in Firefox does not necessarily get the value, e. which is used instead.
Keyup is used to handle the problem of Inputting Chinese characters or letters when using the input method.
Use String. fromCharCode () to obtain the characters corresponding to the ASCII code.
I hope this article will help you design javascript programs.