When doing web development, sometimes you need to perform some operations based on the keyboard, such as submitting a form when pressing Enter, prohibiting users from entering certain special characters, setting shortcut keys, etc. At this time, you need to find out which keys the user pressed and write a small program to test the keys.
$(document).ready(function( ){
var $down = $("#down");
var $press = $("#press");
var $up = $("#up");
$(document).keydown(function(event){
$down.append(String.fromCharCode(event.keyCode) " ");
if (event.ctrlKey) {
alert("ctrl" );
}
}).keyup(function(event){
$up.append(String.fromCharCode(event.keyCode) " ");
}).keypress(function(event ){
$press.append(String.fromCharCode(event.keyCode) " ");
});
});
method is to trigger down. Push keyCode into the array and delete duplicate elements; when up is triggered, use $.grep to delete the keyCode from the array.
At any time, this array stores the currently pressed keys, and the order is based on the key sequence.
Use jQuery to determine the currently pressed keyThe method is to use an external array to save the current key.
When keydown is triggered, push the keyCode into the array and delete duplicate elements; when keyup is triggered, use $.grep to delete the keyCode from the array.
The implementation code is as follows:
Current key :
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