The examples in this article describe the way JavaScript controls input-time format. Share to everyone for your reference. The specific analysis is as follows:
Previously, I did a JavaScript control time format input, the main use of KeyDown and KeyUp two events, but the feeling is very complex to write and there are bugs.
Today I learned the difference between KeyPress events and KeyDown and KeyUp. Roughly as follows (currently only known so much):
KeyDown: Press the button when the trigger, through the event can get to the keycode, you can get to the text box before the value of input;
KeyUp: trigger when the key eject (loosen), can get to keycode through event, can get to the value after the text box enters;
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 can be pressed in the text box will trigger (such as input letters, numbers, symbols, etc.), through the event can get to keycode,event.key as undefined; characters cannot be triggered (such as arrow keys, Home, BACKSPACE, etc.)
2, in Firefox: Letters, numbers, symbols, direction, backspace and other keys can trigger, can get the key by Event.key, if the key can be pressed to output characters are Event.keycode 0, if you can not output characters event.keycode for the corresponding ASCII code
To get back to the point, look directly at the code (the event mentioned above is equivalent to E in the following code):
Copy Code code 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 triggers the KeyPress event, and in Ie/chrome only the keystrokes that are able to output characters are triggered
For Firefox, E.keycode!==0 pressed the backspace, direction, home and so on one of the 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;
}
}
});
Through the ISFF && e.keycode!== 0来 distinguish Firefox can output characters of keystrokes and can not output characters of the key, because Firefox E.keycode may not be able to take the value, so the use of E.which to replace.
KeyUp is used to deal with the problem of typing Chinese or letters when using IME.
Get the character of the ASCII code by String.fromCharCode ().
I hope this article will help you with your JavaScript programming.