ในการตรวจสอบการกดแป้นลูกศรใน 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>
ผลลัพธ์
เมื่อกดปุ่มลูกศรใดๆ −