日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

JavaScript响应键盘不再用KeyboardEvent.keyCode,而是用keyboardEvent.code

發布時間:2025/4/5 javascript 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JavaScript响应键盘不再用KeyboardEvent.keyCode,而是用keyboardEvent.code 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • 遇到問題
  • 解決方法
  • 參考

遇到問題

以Wordle為例進行的TDD開發, 現在進展到GUI的階段,遇到的問題是,如何用JS響應鍵盤?

查到的樣例是

document.addEventListener('keydown', (event) => {if (event.ctrlKey) {if (event.keyCode == 65 || event.keyCode == 97) {console.log("You have just pressed Ctrl + a/A!");}} }, false);

Firstly, ctrlKey is a special property of the KeyboardEvent object, which tells you whether the Ctrl key was pressed when the keydown event was triggered. So if ctrlKey is true, it means that the Ctrl key was pressed.
Next, we checked the keyCode value of the character which was pressed, if it’s either 65 or 97, it means that either a or A was pressed along with the Ctrl key. The keyCode property of the KeyboardEvent object returns the Unicode character code of the key which was pressed. Similarly, you can also use the shiftKey property of the KeyboardEvent object, which tells you whether the Shift key was pressed when the key down event was triggered.

但是發現 這個property已經 deprecated

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

解決方法

You should avoid using this if possible; it’s been deprecated for some time. Instead, you should use KeyboardEvent.code, if it’s implemented. Unfortunately, some browsers still don’t have it, so you’ll have to be careful to make sure you use one which is supported on all target browsers.

使用KeyboardEvent.code property 如下

document.addEventListener('keydown', (event) => {if (event.ctrlKey) {if (event.code === "KeyA") {console.log("You have just pressed Ctrl + a/A!");}}}, false);

console輸出結果

參考

[1]https://developer.mozilla.org/en-US/docs/web/api/keyboardevent/keycode#browser_compatibility

[2]Catching and Responding to Keyboard Events in JavaScript

《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的JavaScript响应键盘不再用KeyboardEvent.keyCode,而是用keyboardEvent.code的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。