During web development, you sometimes need to perform some operations based on the keyboard, such as submitting a form when you press Enter, prohibiting users from entering certain special characters, and setting shortcuts. At this time, you need to find out the keys that the user presses and write a applet to test the keys.
Copy codeThe Code is as follows:
$ (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) + "");
});
});
When the trigger is down, the keyCode is pushed to the array and the repeated elements are deleted. When the trigger is up, $. grep is used to delete the keyCode from the array.
At any time, the array stores the previously pressed keys, which are arranged in the order of keys.
Use jQuery to determine the buttons currently pressed
The method is to use an external array to save the current button.
When keydown is triggered, the keyCode is pushed to the array and repeated elements are deleted. When keyup is triggered, $. grep is used to delete the keyCode from the array.
The implementation code is as follows:
Copy codeThe Code is as follows:
Current button: <span id = "msg"> </span>
<Script type = "text/javascript">
Array. prototype. unique = function () {// This is used to delete duplicate elements. Unfortunately, $. unique can only process DOM arrays.
Var o = {};
For (var I = 0, j = 0; I <this. length; ++ I ){
If (o [this [I] === undefined ){
O [this [I] = j ++;
}
}
This. length = 0;
For (var key in o ){
This [o [key] = key;
}
Return this;
};
Var $ msg = $ ('# msg ');
Var keys = [];
$ (Document). keydown (function (event ){
Keys. push (event. keyCode );
Keys. unique ();
$Msg.html (keys. join (''));
}). Keyup (function (event ){
Keys. push (event. keyCode );
Keys = $. grep (keys, function (n) {return n! = Event. keyCode ;});
$Msg.html (keys. join (''));
});
</Script>