Most of the time, we need to get the user's keyboard events, and here's a look at how jquery operates keyboard events.
First, need to know is:
1 , KeyDown ()
The KeyDown event is triggered when the keyboard is pressed.
2 , KeyUp ()
The KeyUp event is triggered when the key is released, which is the event you press the keyboard up
3 , KeyPress ()
The KeyPress event is triggered when the button is tapped, and we can understand that pressing and lifting the same button
Second, obtain the corresponding ASCII code on the keyboard:
123 |
$(document).keydown( function (event){ console.log(event.keyCode); }); |
$tips: In the example above, Event.keycode can help us to get to what button we pressed on the keyboard, he returned the ASCII code, such as the next key around, is 38,40,37,39;
Iii. instances (when pressing the left and right side keys on the keyboard)
12345678910111213 |
$(document).keydown(
function
(event){
//判断当event.keyCode 为37时(即左方面键),执行函数to_left();
//判断当event.keyCode 为39时(即右方面键),执行函数to_right();
if
(event.keyCode == 37){
//do something;
}
else
if (event.keyCode == 39){
//do something;
}
});
|
Case studies:
For example: The novel Web site common to the right and left to achieve the previous article and the next article; Press CTRL + ENTER to implement the form submission; Google Reader and Youdao reading in the full shortcut key operation ... (To improve the user experience)
① implementation Ctrl+enter is CTRL + ENTER submit form:
1234567 |
$(document).keypress( function (event) { if (event.ctrlKey && event.which == 13) $( "form:first" ).trigger( "submit" ); }) |
② Monitor CTRL key:
123456789 |
$(document).keydown( function (event){ //(ctrlKey和metaKey等效:都是监测)按下ctrl返回turn,按下非ctrl键返回false; console.log(event.ctrlKey); //console.log(event.metaKey); }) |
③ Keyboard Series operation
12345678910111213141516171819202122232425 |
$(document).keydown(
function
(event){
var
e = event || window.event;
//作用???
var
k = e.keyCode || e.which;
//获取按键的acdII 码
switch
(k) {
case
37:
//…
break
;
case
39:
//…
break
;
}
return
false
;
})
|
1234567891011 |
//also found an application method: When the page is reprinted, the first FORM element gets the focus in order to enter $ ( "Input[type=text]:first" "focus" ); //When the form does not get the focus, but when the user presses the keyboard, the user is automatically positioned to focus on the input box $ (document) . KeyDown ( function () {         $ ( "Input[type=text]:first" ). Trigger ( |
The above is a common way to list jquery keyboard events, and many times it should be enough.
jquery Keyboard Event Full record