First, what you need to know is:
1, KeyDown ()
The KeyDown event is triggered when the keyboard is pressed.
2, KeyUp ()
The code is as follows |
Copy Code |
$ (' input '). KeyUp (Funciton () { Alert (' KeyUp function is running!! '); }); |
The KeyUp event triggers when the key is released, which is what happens when you press the keyboard
3, KeyPress ()
KeyPress () events and KeyDown are similar, with only one exception, if you need to block the default behavior of keystrokes, you must be yo on KeyPress event
Example 1
The code is as follows |
Copy Code |
$ (selector). KeyDown (function (event) { var key_code = Event.keycode; if (key_code==13) { XXXXXX (); } }); |
Event.keycode can get the current button code, use the following.
Instance
The code is as follows |
Copy Code |
$ (document). KeyDown (function (event) { Console.log (Event.keycode); }); |
$tips: In the example above, Event.keycode can help us to get what we pressed on the keyboard, he returned the ASCII code, such as up and down key, respectively, is 38,40,37,39;
Iii. instance (when pressing the left and right side keys on the keyboard)
The code is as follows |
Copy Code |
$ (document). KeyDown (function (event) { Judge when Event.keycode is 37 o'clock (that is, left side key), execute function to_left (); Judge when Event.keycode is 39 o'clock (that is, right side key), execute function to_right (); if (Event.keycode = = 37) { do somethings; }else if (Event.keycode = = 39) { do somethings; } }); |
Attention
In jquery, Keydown,keypress,keyup events are performed in a certain order.
code is as follows |
copy code |
$ (' input '). KeyUp (function () { console.log (' KeyUp '); }); $ (' input '). KeyDown (function () { console.log (' KeyDown '); }); $ (' input '). KeyPress (function () { console.log (' keypress '); }); |
The
Execution results are: KeyDown, KeyPress, KeyUp.