I. First, you need to know:
1. keydown ()
The keydown event is triggered when the keyboard is pressed.
2. keyup ()
The keyup event is triggered when the key is released, that is, the event after you press the keyboard.
3. keypress ()
The keypress event is triggered when you press a key. We can understand it as pressing and lifting the same key.
2. Obtain the ascII code corresponding to the keyboard:
Copy codeThe Code is as follows: $ (document). keydown (function (event ){
Console. log (event. keyCode );
});
$ Tips: in the preceding example, event. the keyCode can help us obtain the keys on the keyboard that we press. The returned ascII code is, for example, the top, bottom, and left keys are, and 39;
Iii. instance (when the left and right sides of the keyboard are pressed)
Copy codeThe Code is as follows: $ (document). keydown (function (event ){
// When event. keyCode is 37 (that is, the left side Key), The to_left () function is executed ();
// When event. keyCode is 39 (that is, the right side Key), The to_right () function is executed ();
If (event. keyCode = 37 ){
// Do somethings;
} Else if (event. keyCode = 39 ){
// Do somethings;
}
});
Case study:
For example, in a novel website, you can press the left and right keys to implement the previous article and the next article. Press ctrl + press enter to submit the form. google reader and youdao reading all shortcut keys... (to improve user experience)
If we want to implement ctrl + Enter, that is, ctrl + press Enter to submit the form, we can do this:Copy codeThe Code is as follows: $ (document). keypress (function (e ){
If (e. ctrlKey & e. which = 13)
$ ("Form"). submit ();
})
// Keyboard operation
$ (Document). keydown (function (event ){
Var e = event | window. event;
Var k = e. keyCode | e. which;
Switch (k ){
Case 37:
//...
Break;
Case 39:
//...
Break;
}
Return false;
})
A more detailed summary and presentation of the event: http://www.jb51.net/article/28772.htm
JQuery event reference manual on w3school
During the learning process, we should think more about how to improve interaction and user experience.