在 JavaScript 中处理键盘
1.动作函数列表
使用您想要的函数创建一个对象文字列表。假设您有一个要移动的角色,这里有一些示例Actions:
const Action = {
powerOn() { console.log("Accelerating..."); },
powerOff() { console.log("Decelerating..."); },
brakeOn() { console.log("Break activated"); },
brakeOff() { console.log("Break released"); },
exit() { console.log("Nice drive!"); },
// clutch, colors, lights, fire... Add more, go wild!
};
PS:在真实情况下,每个函数都将包含处理字符的实际逻辑,它是一次性的"move-by-N-px",或者充当填充队列的代理,而不是消耗通过像Window.requestAnimationFrame这样的帧率引擎。您还可以创建函数来更改颜色等。您了解了总体思路。
2. 通过 Event.type 将键关联到操作
将 KeyboardEvent.key 关联到所需 Event.type 的所需操作(←必须为小写):
const keyAction = {
w: { keydown: Action.powerOn, keyup: Action.powerOff },
s: { keydown: Action.brakeOn, keyup: Action.brakeOff },
Escape: { keydown: Action.exit }
};
请注意,键名"w"
"s"
"Escape"
表示为首选 KeyboardEvent.key
的返回值,而不是数字KeyboardEvent.keyCode
。我们是人,不是机器人。
3. 键盘事件处理程序
最后,让我们监听"keyup"
"keydown"
Events并触发一个回调函数keyHandler
,它最终会触发我们具体的Action函数,比如说ie:keyAction["w"]["keydown"]()
这实际上是我们飞船的powerOn
Action函数!
const keyHandler = (ev) => {
if (ev.repeat) return; // Key-held, prevent repeated Actions (Does not work in IE11-)
if (!(ev.key in keyAction) || !(ev.type in keyAction[ev.key])) return; // No such Action
keyAction[ev.key][ev.type](); // Trigger an Action
};
['keydown', 'keyup'].forEach((evType) => {
document.body.addEventListener(evType, keyHandler);
});
结果:
const Action = {
powerOn() { console.log("Accelerating..."); },
powerOff() { console.log("Decelerating..."); },
brakeOn() { console.log("Break activated"); },
brakeOff() { console.log("Break released"); },
exit() { console.log("Nice drive!"); },
};
const keyAction = {
w: { keydown: Action.powerOn, keyup: Action.powerOff },
s: { keydown: Action.brakeOn, keyup: Action.brakeOff },
Escape: { keydown: Action.exit }
};
const keyHandler = (ev) => {
if (ev.repeat) return;
if (!(ev.key in keyAction) || !(ev.type in keyAction[ev.key])) return;
keyAction[ev.key][ev.type]();
};
['keydown', 'keyup'].forEach((evType) => {
document.body.addEventListener(evType, keyHandler);
});
Click here to focus this window.<br>
Then, use [<kbd>W</kbd>], [<kbd>S</kbd>] or [<kbd>Esc</kbd>] keys on your keyboard.
您的具体要求的示例:
const changeBG = (color) => document.body.style.background = color;
const Action = {
red() { changeBG("#f00"); },
yellow() { changeBG("yellow"); },
orange() { changeBG("orange"); },
reset() { changeBG(""); },
};
const keyAction = {
r: { keydown: Action.red, keyup: Action.reset },
y: { keydown: Action.yellow, keyup: Action.reset },
o: { keydown: Action.orange }, // No keyup for this one :)
};
const keyHandler = (ev) => {
if (ev.repeat) return;
if (!(ev.key in keyAction) || !(ev.type in keyAction[ev.key])) return;
keyAction[ev.key][ev.type]();
};
['keydown', 'keyup'].forEach((evType) => {
document.body.addEventListener(evType, keyHandler);
});
body { transition: background: 0.3s; }
Click here to focus this window. <br>Keys:<br>
[<kbd>Y</kbd>] for Yellow<br>
[<kbd>R</kbd>] for Red<br>
[<kbd>O</kbd>] to permanently set to Orange