JavaScript - 检测按下箭头键
如需检测 JavaScript 中按下的箭头键,代码如下;
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .sample { font-size: 18px; font-weight: 500; } </style> </head> <body> <h1>Detecting the pressed arrow key</h1> <div class="sample"></div> <h3> Press any arrow key to know which arrow key has been pressed </h3> <script> let fillEle = document.querySelector(".sample"); document.body.addEventListener("keydown", (event) => { switch (event.keyCode) { case 37: fillEle.innerHTML = "Left key pressed"; break; case 38: fillEle.innerHTML = "Up key pressed"; break; case 39: fillEle.innerHTML = "Right key pressed"; break; case 40: fillEle.innerHTML = "Down key pressed"; break; } }); </script> </body> </html>
输出
按下任一箭头键 -
广告