方向鍵控制是遊戲、輪播圖、表格導航、無障礙組件的核心交互。本文系統講解 keydown/keyup 事件、event.key 標準化、長按重複觸發機制、防抖/節流、焦點管理、與 requestAnimationFrame 遊戲循環整合。
| 物理鍵 | event.key | event.code | 舊 event.keyCode |
|---|---|---|---|
| ← | 'ArrowLeft' | 'ArrowLeft' | 37 |
| ↑ | 'ArrowUp' | 'ArrowUp' | 38 |
| → | 'ArrowRight' | 'ArrowRight' | 39 |
| ↓ | 'ArrowDown' | 'ArrowDown' | 40 |
**推薦使用 event.key**(語意化、不受鍵盤佈局影響),event.code 代表物理位置(遊戲 WASD 移動用 code)。
const pressed = new Set();
window.addEventListener('keydown', e => {
if (e.repeat) return; // 忽略瀏覽器自動重複(長按產生的連續 keydown)
pressed.add(e.key);
handleInput();
});
window.addEventListener('keyup', e => {
pressed.delete(e.key);
});
function handleInput() {
if (pressed.has('ArrowLeft')) move(-1, 0);
if (pressed.has('ArrowRight')) move(1, 0);
if (pressed.has('ArrowUp')) move(0, -1);
if (pressed.has('ArrowDown')) move(0, 1);
}
class InputManager {
constructor() {
this.pressed = new Set();
this.justPressed = new Set();
this.justReleased = new Set();
this._bind();
}
_bind() {
window.addEventListener('keydown', e => {
if (!this.pressed.has(e.key)) this.justPressed.add(e.key);
this.pressed.add(e.key);
});
window.addEventListener('keyup', e => {
this.pressed.delete(e.key);
this.justReleased.add(e.key);
});
}
// 每幀調用
update() {
this.justPressed.clear();
this.justReleased.clear();
}
isDown(key) { return this.pressed.has(key); }
wasPressed(key) { return this.justPressed.has(key); }
wasReleased(key) { return this.justReleased.has(key); }
}
// 遊戲主循環
const input = new InputManager();
function gameLoop(timestamp) {
input.update();
if (input.isDown('ArrowLeft')) player.x -= player.speed;
if (input.wasPressed('Space')) player.jump();
render();
requestAnimationFrame(gameLoop);
}
requestAnimationFrame(gameLoop);
const grid = document.querySelector('[role="grid"]');
const cells = [...grid.querySelectorAll('[role="gridcell"]')];
let currentIndex = 0;
grid.addEventListener('keydown', e => {
let newIndex = currentIndex;
const cols = 4; // 假設 4 列
switch (e.key) {
case 'ArrowLeft': newIndex = Math.max(0, currentIndex - 1); break;
case 'ArrowRight': newIndex = Math.min(cells.length - 1, currentIndex + 1); break;
case 'ArrowUp': newIndex = Math.max(0, currentIndex - cols); break;
case 'ArrowDown': newIndex = Math.min(cells.length - 1, currentIndex + cols); break;
case 'Home': newIndex = 0; break;
case 'End': newIndex = cells.length - 1; break;
default: return;
}
e.preventDefault(); // 防止頁面滾動
cells[newIndex].focus();
currentIndex = newIndex;
});
role="grid"/treegrid、role="listbox"、role="menu" 等有明確鍵盤交互規範。