Home > Web Front-end > JS Tutorial > JavaScript method to get which direction key is pressed on the keyboard_javascript skills

JavaScript method to get which direction key is pressed on the keyboard_javascript skills

WBOY
Release: 2016-05-16 15:47:06
Original
1340 people have browsed it

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>

Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template