Home  >  Article  >  Web Front-end  >  Summary of keyboard events in jquery_jquery

Summary of keyboard events in jquery_jquery

WBOY
WBOYOriginal
2016-05-16 15:13:551239browse

1. The first thing you need to know is:

1. keydown()
The keydown event will be triggered when the keyboard is pressed.

2. keyup()
The keyup event will be triggered when the key is released, that is, the event after you press the keyboard and get up

3. keypress()
The keypress event is triggered when a key is tapped. We can understand it as pressing and lifting the same key

2. Obtain the corresponding asciII code on the keyboard:

$(document).keydown(function(event){ 
alert(event.keyCode); 
}); 

$tips: In the above example, event.keyCode can help us get what keys we pressed on the keyboard. It returns the ASCII code, for example, the up, down, left, and right keys are 38, 40, and 37, respectively. 39;

3. Example (when pressing the left and right keys on the keyboard)

The code is as follows:

$(document).keydown(function(event){ 
//判断当event.keyCode 为37时(即左方面键),执行函数to_left(); 
//判断当event.keyCode 为39时(即右方面键),执行函数to_right(); 
 if(event.keyCode == 37){ 
    to_left(); 
    }else if (event.keyCode == 39){
    to_right(); 
    } 
    else if (event.keyCode == 38){ 
    to_top(); 
    } 
    else if (event.keyCode == 40){ 
    to_bottom();
    } 
}); 

function to_left(){ $(".abc").css({'left':'-=10'});}

function to_right(){ $(".abc").css({'left':'+=10'});}

function to_top(){$(".abc").css({'top':'-=10'});}

function to_bottom(){$(".abc").css({'top':'+=10'});}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn