Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Phát hiện phím mũi tên được nhấn trong JavaScript

Để phát hiện phím mũi tên, sử dụng sự kiện onkeydown. Các phím mũi tên có mã key code: Left=37, Up=38, Right=39, Down=40.

Ví dụ

Mã nguồn:

<!DOCTYPE html> <html lang="en"> <head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Document</title> </head> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <body> </body> <script>    document.onkeydown = function (event) {       switch (event.keyCode) {          case 37:             console.log("Left key is pressed.");             break;          case 38:             console.log("Up key is pressed.");             break;          case 39:             console.log("Right key is pressed.");             break;          case 40:             console.log("Down key is pressed.");             break;       }    }; </script> </html>

Lưu file và mở với Live Server.

Kết quả

Ví dụ nhấn phím mũi tên lên, console hiển thị:

Phát hiện phím mũi tên được nhấn trong JavaScript