Home >Web Front-end >JS Tutorial >jQuery simple method to get keyboard events_jquery
The example in this article describes how jQuery simply obtains keyboard events. Share it with everyone for your reference, the details are as follows:
1. When do we need to get keyboard events?
When working on the web, for a more humane design, we sometimes use keyboard events. For example: input box drop-down prompt box, use the up and down keyboard to select the content you want, Google's input box drop-down prompt box. When we browse the photo album, we can use the left and right keys on the keyboard to view the photos. When we browse a long novel, it is easy to lose track of which line to read when scrolling with the mouse. You can use the up and down keys on the keyboard to turn pages. These small details are also very important. Making a website depends largely on the details.
2. Keyboard function types of jquery
1. The keydown event is an event triggered when the keyboard is pressed
2. The keyup event is an event triggered when a key is pressed and the key is released
3. The keypress event is an event triggered when the keyboard is pressed
Keypress and keydown have similar functions, but they are different in obtaining the content of the event.
2. Examples
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" dir="ltr" lang="utf-8"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="jquery-1.3.2.js" type="text/javascript"></script> </head> <body> <input value="fi" name="search" id="search_input" maxlength="50" autocomplete="off"> </body> </html> <script type="text/javascript"> $('#search_input') .keypress(function(event){ alert("keypress"); }) .keydown(function(event){ alert("keydown"); }) .keyup(function(event){ alert("keyup"); }); </script>
3. Test results
1. In the above input box, when entering a letter r, keydown will pop up for the first time, and keypress will be prompted in the future
2. When we press pg dn銉, keyup will pop up first and then keydown
3. When we press shift+c, only keypress
will pop up
4. When we press ctrl+alt, keypress will not appear. Two keydowns will appear for the first time. When we press it for the second time, keyup will appear first, and then keydown
There are many possibilities, we just need to try the commonly used phoenix.
4. Obtain the ASCII value corresponding to the keyboard event
<script type="text/javascript"> $('#search_input') .keydown(function(event){ alert(event.keyCode); }) </script>
Readers who are interested in more content related to jQuery event operations can check out this site's special topic: "Summary of jQuery common event usage and techniques"
I hope this article will be helpful to everyone in jQuery programming.