萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

鍵盤方向鍵控制交互:事件監聽、key 值標準化、防重複觸發、焦點管理與遊戲循環整合

方向鍵控制是遊戲、輪播圖、表格導航、無障礙組件的核心交互。本文系統講解 keydown/keyup 事件、event.key 標準化、長按重複觸發機制、防抖/節流、焦點管理、與 requestAnimationFrame 遊戲循環整合。

標準鍵值對照表

物理鍵event.keyevent.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;
});

無障礙:ARIA 鍵盤交互模式

  • 遵循 WAI-ARIA Authoring Practices:Tab 進入組件、方向鍵內部導航、Tab 離開組件。
  • role="grid"/treegrid、role="listbox"、role="menu" 等有明確鍵盤交互規範。
copyright © 萬盛學電腦網 all rights reserved