The example in this article describes the method of Javascript controlling the input time format. Share it with everyone for your reference. The specific analysis is as follows:
I made a Javascript control time format input before, mainly using 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 event, keydown and keyup. It's roughly as follows (I only know this much so far):
keydown: Triggered when the key is pressed. The keyCode can be obtained through the event, and the value before the text box is entered can be obtained;
keyup: Triggered when the key is popped up (released). The keyCode can be obtained through the event, and the value after input into the text box can be obtained;
keypress: This event is basically the same in Chrome and IE, but Firefox is a little different;
1. In Chrome and IE: As long as the pressed key can appear characters in the text box, it will be triggered (such as entering letters, numbers, symbols, etc.). The keyCode can be obtained through event, and event.key is undefined; Characters that cannot appear will not be triggered (such as arrow keys, Home, Backspace, etc.)
2. In Firefox: letters, numbers, symbols, directions, backspace and other keys can be triggered, and the key name can be obtained through event.key. If the key pressed can output characters, event.keyCode is 0. If characters cannot be output, event.keyCode is the corresponding ASCII code
Back to the topic, let’s look at the code directly (the event mentioned above is equivalent to e in the code below):
Use isFF && e.keyCode !== 0 to distinguish the keys that can output characters in Firefox and the keys that cannot output characters. Since e.keyCode in Firefox may not be able to get the value, e.which is used instead.
keyup is used to solve the problem of being able to input Chinese or letters when using the input method.
Get the character corresponding to the ASCII code through String.fromCharCode().
I hope this article will be helpful to everyone’s JavaScript programming design.