Summary of keyboard events in jquery

  • 2021-01-03 20:48:19
  • OfStack

1. The first thing 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, which is what happens when you press the keyboard up

3, keypress ()
The keypress event is triggered when a key is struck, which can be interpreted as pressing and lifting the same key

2. Obtain the corresponding ascII code on the keyboard:


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

$tips: in the above example, event.keyCode will help us get what key we pressed on the keyboard, and it will return the ascII code, such as the left, right, and top keys, respectively 38,40,37,39;

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

The code is as follows:


$(document).keydown(function(event){ 
// To determine when event.keyCode  for 37 , the left aspect key, executes the function to_left(); 
// To determine when event.keyCode  for 39 , the right aspect key, executes the function 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'});}


Related articles: