概述
如果你想让你的页面监听你的键盘事件,你可以使用 window.addEventListener
函数来全局监听你的键盘事件,如果你想要单独监听某个 dom 的按键事件,你可以使用 document.getElementByID('yourDomId').addEventListener
来添加监听
示例
let left = {
key: ["a", "A"],
isDown: false,
isUp: true,
pressEvent: function (e, obj) {
if (this.key.includes(e.key)) {
this.isDown = true;
this.isUp = false;
}
},
releaseEvent: function (e, obj) {
if (this.key.includes(e.key)) {
this.isDown = false;
this.isUp = true;
}
},
};
let keyboard = [left];
window.addEventListener("keydown", function (event) {
keyboard.forEach((item) => {
item.pressEvent(event, userInput);
});
});
window.addEventListener("keyup", function (event) {
keyboard.forEach((item) => {
item.releaseEvent(event, userInput);
});
});