遇到问题
以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