JS keyboard event to determine which key is pressed

Source: Internet
Author: User

When writing the page, especially the desktop side, we sometimes have to know that the user pressed the button, for this problem we can use JS provided by the KeyCode properties to operate, such as:


Document.onkeydown = function (e) {
Alert (E.keycode)
}

At this time you are free to press the keyboard button on the page, will pop a pop-up window, which corresponds to the number of keys you press the KeyCode, this keycode is fixed, so we can use its value to judge, and then do some operations.

Document.onkeydown = function (e) {
if (E.keycode = = 13) {
Alert (' You press the OK key ');
}
if (E.keycode = = 84) {
Alert (' You pressed the T-key ');
}
}

To determine the keyboard up and down key events

Document.onkeydown=function (event) {
var e = Event | | window.event | | Arguments.callee.caller.arguments[0];

if (e && e.keycode==38 | | | e && e.keycode==37) {//up, left
Alert (' 38 = up key, 37 = left button ');
}

if (e && e.keycode==40 | | | e && e.keycode==39) {//down, right
Alert (' 38 = Next key, 37 = Right key ');
}
};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.