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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值