You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mac下按住Meta键时Keyup事件不触发的JavaScript解决方案求助

Mac下Command键组合键后Keyup事件延迟导致的按键状态误判问题

在Mac系统中存在一个特殊行为:按住Command键(即Meta键)并按下再松开其他按键(比如Command-C复制文本)时,被松开的那个按键的Keyup事件不会立即触发,必须等先松开Command键才会触发。

这个问题影响了我的Web应用:应用通过Alt-X组合键切换菜单,我用Keydown和Keyup事件跟踪实时按键状态,目的是确保只有在单独输入Alt-X时才切换菜单,而非包含Alt-X的其他组合键。但在执行过Command+某键的操作后,再按Alt-X时,程序会误判当前是包含之前那个按键的组合键,导致功能异常。

我制作了演示代码来复现这个问题:

JavaScript代码

const pressed_keys = {};

const keydown_handler = e => {
  pressed_keys[e.code] = true;
  if (has_entered_alt_x(e)) {
    document.querySelector('div').classList.toggle('blue');
  }
};

const keyup_handler = e => pressed_keys[e.code] = false;

const has_entered_alt_x = e => {
  if (!(e.altKey && e.code == 'KeyX')) return false;

  for (const key in pressed_keys) {
    if (Object.hasOwnProperty.call(pressed_keys, key)) {
      if (!['AltLeft', 'AltRight', 'KeyX', 'CapsLock'].includes(key) && 
          pressed_keys[key]) {
        return false;
      }                    
    }
  }

  return true;
}

document.addEventListener('DOMContentLoaded', () => { 
  document.addEventListener('keydown', keydown_handler);
  document.addEventListener('keyup', keyup_handler);
});

CSS代码

div {
  width: 40px;
  height: 40px;
  background-color: red;
}

.blue {
  background-color: blue;
}

HTML代码

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8"/>
  </head>
  <body>
    <div></div>
  </body>
</html>

请问有什么解决思路吗?

内容的提问来源于stack exchange,提问作者Duncan Britt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 05:06:28