如何在 JavaScript 中找出按鍵的字元名稱?
為了找出按下的是哪個字元鍵,請同時使用 window.event 和 keyCode。以下為程式碼 −
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale= 1.0"> <title>Document</title> <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> </head> <body> <form> <input type="text" onkeypress="return keyPressName(event)" /> </form> <script> function keyPressName(myEventKeyName){ var pressedKey; if(window.event){ pressedKey = myEventKeyName.keyCode; } else if(myEventKeyName.which) { pressedKey = myEventKeyName.which; } alert(String.fromCharCode(pressedKey)); } </script> </body> </html>
要執行上述程式,請將檔案儲存為“anyName.html(index.html)”並右鍵單擊該檔案。在 VS Code 編輯器中選擇“使用 Live Server 開啟”選項。
輸出
這將生成以下輸出 −
這裡,我按下了字元 g。這將生成以下輸出 −
在顯示字元 g 後,單擊確定按鈕,然後你將獲得以下輸出。
廣告