現代標準:使用 event.key 和 event.code
document.addEventListener('keydown', function(e) {
// 推薦:key 返回字符(含修飾鍵組合),code 返回物理鍵位
console.log('key:', e.key, 'code:', e.code, 'ctrl:', e.ctrlKey, 'shift:', e.shiftKey, 'alt:', e.altKey);
// 常用功能鍵判斷
switch (e.key) {
case 'Escape': case 'Esc': handleEsc(); break;
case 'Enter': handleEnter(); break;
case 'F2': handleF2(); break;
case 'ArrowUp': case 'ArrowDown': case 'ArrowLeft': case 'ArrowRight': handleArrow(e.key); break;
case 'Tab': handleTab(e.shiftKey); break;
case 'Delete': case 'Backspace': handleDelete(); break;
}
// 組合鍵
if (e.ctrlKey && e.key === 's') { e.preventDefault(); save(); }
if (e.ctrlKey && e.shiftKey && e.key === 'z') { redo(); }
});
常用鍵值速查表
| 功能 | e.key | e.code | 舊 keyCode (棄用) |
| Enter | Enter | Enter | 13 |
| Esc | Escape | Escape | 27 |
| 空格 | | Space | 32 |
| Backspace | Backspace | Backspace | 8 |
| Delete | Delete | Delete | 46 |
| Tab | Tab | Tab | 9 |
| 方向鍵 | ArrowUp/Down/Left/Right | ArrowUp/Down/Left/Right | 38/40/37/39 |
| F1-F12 | F1...F12 | F1...F12 | 112-123 |
| 數字鍵 | 0-9 | Digit0-9 | 48-57 |
| 字母鍵 | a-z (小寫) | KeyA-KeyZ | 65-90 |
| 修飾鍵 | Control/Shift/Alt/Meta | ControlLeft/Right... | 17/16/18/91 |
避坑指南
- 棄用
keyCode/which/charCode:已從標準移除,僅為兼容保留,不同瀏覽器行為不一。
- 區分
key vs code:
key:語義字符(如輸入 'a' 時為 'a',Shift+'a' 為 'A',中文輸入法下為組合字符)。
code:物理鍵位(美式鍵盤 'KeyA' 固定對應 A 鍵位,無論輸入法、修飾鍵)。遊戲、快捷鍵映射請用 code。
- 輸入法合成事件:中文/日文輸入時會觸發
compositionstart/update/end,keydown 的 key 可能為 Process 或拼音字母,**文本輸入請監聽 input 事件**。
- 全局快捷鍵:綁定在
window 或 document,並在處理函數中檢查 e.target.isContentEditable 或 e.target.tagName === 'INPUT/TEXTAREA' 以避免干擾正常輸入。
完整鍵盤快捷鍵管理器示例
class HotkeyManager {
constructor() {
this.map = new Map(); // 'ctrl+s' -> handler
this.handler = e => this.dispatch(e);
document.addEventListener('keydown', this.handler);
}
register(keys, handler, options = {}) {
// keys: 'ctrl+s', 'shift+alt+f', 'f2', 'arrowup'
const normalized = keys.toLowerCase().replace(/\s+/g, '').split('+').sort().join('+');
this.map.set(normalized, { handler, ...options });
}
unregister(keys) {
const normalized = keys.toLowerCase().replace(/\s+/g, '').split('+').sort().join('+');
this.map.delete(normalized);
}
dispatch(e) {
// 構建當前組合鍵字符串
const parts = [];
if (e.ctrlKey) parts.push('ctrl');
if (e.shiftKey) parts.push('shift');
if (e.altKey) parts.push('alt');
if (e.metaKey) parts.push('meta');
parts.push(e.key.toLowerCase());
const combo = parts.sort().join('+');
const entry = this.map.get(combo);
if (entry) {
if (!entry.allowInInput && this.isInputTarget(e.target)) return;
e.preventDefault();
entry.handler(e);
}
}
isInputTarget(el) {
return el.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(el.tagName);
}
destroy() { document.removeEventListener('keydown', this.handler); }
}
// 使用
const hotkeys = new HotkeyManager();
hotkeys.register('ctrl+s', () => saveDoc());
hotkeys.register('f2', () => renameItem());
hotkeys.register('ctrl+shift+z', () => redo());