You often need to listen to events on your keyboard for better operation, the basic principle is: listening to the global keyboard, each keyboard, when the user presses a key, return the corresponding key value, and then judge the user pressed which section of the button, the key value corresponding to the key keys listed below, their own comparison. Go to the following to introduce two different ways
Primary keyboard Listener event: Press the key once, divided into three processes, press-hold-release
OnKeyDown: A key was pressed
onkeypress: The key of a keyboard is pressed or held down
OnKeyUp: Key of a keyboard is loosened
Using the method, in general, keyboard monitoring is directly on the entire page of the document monitoring, that is, document
The following is a native use case
Actually use
document.onkeydown=function (e) { //monitor the entire page document for
var keynum=window.event? E.keycode:e.which; Gets the key value that was pressed
if (keynum==13) {
alert (' You pressed enter ');
}
Determine if the user presses the SPACEBAR (KEYCODE=32), if
(keynum==32) {
alert (' You have pressed a space ');
The other two key methods are the same.
jquery way to listen for keyboard events
jquery is also divided into three processes, but the event name is different
KeyUp: Key of a keyboard is loosened
KeyDown: A key was pressed
KeyPress: The key of a keyboard is pressed or held down
How to use:
$ (document). KeyUp (function (event) {
switch (event.keycode) {
case: alert (' You pressed enter ');
return;
Case: Alert (' You have pressed a space ');
return;
}
Summary: Overall, the results of both approaches are the same, but because jquery is easier to get objects, it is generally more recommended to use jquery, of course, if you have a jquery base.
The above is small series for everyone to bring JS monitoring keyboard events _ native and jquery the difference between the whole content, I hope that we support cloud Habitat Community ~