The example in this article describes how JavaScript can obtain which direction key is pressed on the keyboard. Share it with everyone for your reference. The details are as follows:
By creating an event.keyCode object, you can effectively obtain the direction keys on the keyboard. After running the code, click any direction key on the keyboard, and the web page will return which key you pressed in the form of Alert.
The operation effect is as shown below:
The specific code is as follows:
<html> <head> <title>取得键盘的方向键</title> <script language="javascript"> <!-- function showkey(){ key = event.keyCode; if (key == 37) alert("按了←键!"); if (key == 38) alert("按了↑键!"); if (key == 39) alert("按了→键!"); if (key == 40) alert("按了↓键!"); } document.onkeydown=showkey; --> </script> </head> <body> 请按方向键←↑→↓ </body> </html>
I hope this article will be helpful to everyone’s JavaScript programming design.