javascript
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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IDEA2021.03 项目全部变红,但
- 下一篇: SVN版本控制如何删除文件或者文件夹?