如何检测同时按下的两个字符(键)

How To Detect Two Characters (Keys) Pressed At The Same TIme

一个重要的区别是,更容易知道是否同时按下 cntrlz,但不能直接检测是否 zx 同时按下。检测同时按下多个字符的最佳方法是什么?

此示例使用事件侦听器来跟踪包含当前按下的所有键的对象。

我们可以使用这个对象来检查是否按下了某些键。这意味着我们可以检测到用户键盘允许的同时按键次数。

重要的是,它可以让您检测何时同时按下多个字符。

const keysPressed = {};

document.addEventListener('keydown', (event) => {
  if (!event.repeat)
    keysPressed[event.key] = true;
  
  //You can also include event.repeat as a condition in your cases if you wish an event to only occur once each trigger.
  //You can also include Object.keys(keysPressed).length === 2 (for example) if you only wish the case to be valid if just two keys are pressed.
  //Finally, instead of event.key === 'x' you can write keysPressed['x']. This would replace both non-default cases in the example. The result is that the event will continue firing if another key is pressed.
  switch (true) { //You use true here because we are using logic to determine each case
    case event.key === 'x' && keysPressed['z']:
    case event.key === 'z' && keysPressed['x']:
      console.log('Z and X pressed!');
      break;
    default:
      break;
  }
});

document.addEventListener('keyup', (event) => {
  if (!event.repeat)
    delete keysPressed[event.key];
});

我只是使用一个数组来存储所有按下的键。当键被释放时,这个数组被清除为空状态。

在 keydown 事件侦听器中,您可以将函数与您要实现的逻辑挂钩。读取 keys 数组以检查所有当前按下的键。

const keys = []
document.addEventListener('keydown', e => {
  !event.repeat && keys.push(e.key)
  doSomethingWithKeys(keys)
})
document.addEventListener('keyup', e => {
  keys.splice(0, keys.length)
})

function doSomethingWithKeys(keys) {
  console.log('keys pressed:', keys.join('+'))
}