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

JS新手求助:实现数字钢琴同步按键分组的自定义HTML文本框

数字钢琴按键分组实现方案

核心思路是通过监听键盘的keydown和keyup事件,维护当前按下的按键集合,区分单次按键与组合按键,最终输出要求的格式。

关键变量说明

  • currentPressed:用Set存储当前处于按下状态的按键,自动去重,避免重复触发keydown事件导致的重复记录
  • output:存储最终输出的片段数组,最后拼接成字符串
  • isGrouping:标记是否处于组合按键状态,避免重复添加组合片段

完整实现代码

<!DOCTYPE html>
<html>
<body>
  <div id="output"></div>
  <script>
    const currentPressed = new Set();
    const output = [];
    let isGrouping = false;

    document.addEventListener('keydown', (e) => {
      // 只处理字母键,可根据需求扩展
      if (!/^[a-z]$/i.test(e.key)) return;
      const key = e.key.toLowerCase();
      
      if (!currentPressed.has(key)) {
        currentPressed.add(key);
        if (!isGrouping) {
          isGrouping = true;
        }
      }
    });

    document.addEventListener('keyup', (e) => {
      const key = e.key.toLowerCase();
      if (!currentPressed.has(key)) return;

      currentPressed.delete(key);

      // 当当前按下集合为空,说明这组按键结束
      if (currentPressed.size === 0) {
        // 如果是单个按键,直接加入输出
        if (output.length === 0 || !output[output.length - 1].startsWith('[')) {
          output.push(key);
        } else {
          // 如果是组合按键的最后一个,补全括号
          const last = output.pop();
          output.push(`${last}${key}]`);
        }
        isGrouping = false;
      } else {
        // 如果还有其他按键按着,且还没添加组合起始标记,添加[
        if (!isGrouping) {
          isGrouping = true;
          output.push(`[${key}`);
        } else {
          // 组合中添加后续按键
          const last = output.pop();
          output.push(`${last}${key}`);
        }
      }

      // 更新页面显示,用空格分隔片段
      document.getElementById('output').textContent = output.join(' ');
    });
  </script>
</body>
</html>

逻辑解释

  1. 按键按下时:只记录未在集合中的字母键,标记进入可能的组合状态
  2. 按键释放时:
    • 若释放后无其他按键按下:
      • 之前是单键则直接加入输出
      • 之前是组合键则补全括号后加入输出
    • 若释放后仍有其他按键按下:
      • 首次进入组合则添加[起始标记
      • 组合中则追加当前按键到组合片段

测试验证

按顺序执行:按下a→松开a→按下b→松开b→同时按下c和d→松开c→松开d,页面会输出 a b [cd],符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 20:33:23