← 中文资源

简体中文版本

KeyboardEvent 区分 key 与 code

event.key 是布局解释后的字符,event.code 是物理键位:快捷键判断用 code 才不受键盘布局影响,Enter 提交这类语义判断用 key 并排除 IME 组合状态。

阅读英文原文

实现说明

这个示例中仅有的重复出现在 for (const press of presses) input.dispatchEvent(press); 里。 演示用的数据放在这几个模块级绑定中:input、actions、presses。

使用要点

  • document 只存在于浏览器——Node 运行时没有现成的垫片。
  • 跑完文件,输出里会留下标记——actions:。

常见问题

「KeyboardEvent 区分 key 与 code」能在裸 Node.js 里跑吗?

不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。

代码示例

// event.key is the character after layout/IME interpretation, while event.code is the physical key (named for its US-layout position):
// shortcut matching uses code to stay layout-independent; semantic checks like Enter-to-submit use key and exclude IME composition
const input = document.createElement('input');
document.body.append(input);
const actions = [];

input.addEventListener('keydown', (event) => {
  if (event.ctrlKey && event.code === 'KeyS') actions.push('save');
  else if (event.key === 'Escape') actions.push('close');
  else if (event.key === 'Enter') {
    // Enter during IME composition confirms the candidate instead of submitting
    actions.push(event.isComposing ? 'ignore-ime' : 'submit');
  } else actions.push('none');
});

// on AZERTY the physical key labelled Q (code 'KeyA') produces the character 'q' — key follows the layout, code does not
const presses = [
  new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter' }),
  new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', isComposing: true }),
  new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape' }),
  new KeyboardEvent('keydown', { key: 's', code: 'KeyS', ctrlKey: true }),
  new KeyboardEvent('keydown', { key: 'q', code: 'KeyA', ctrlKey: true }),
];
for (const press of presses) input.dispatchEvent(press);
console.log('actions:', actions.join(','));