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

网页钢琴移调功能失效:JavaScript修改data-note属性的问题

Web钢琴合成器移调功能修复

问题分析

你当前的OctaveShift函数错误操作了piano容器元素(<ul id="piano">),但这个容器本身没有data-note属性——真正存储音符信息的是它内部的<li class="key">(白键)和<div class="black-key">(黑键)元素。因此点击按钮后没有修改到实际按键的音符数据,导致音高无变化。

解决方案

1. 修正OctaveShift函数

要修改所有按键的data-note属性,需先获取所有带该属性的元素,再逐个更新。以下提供两种实现方式:

方式一:将所有按键统一改为C5(符合你最初的期望)

function OctaveShift(){
  // 获取所有带data-note属性的元素(包含白键和黑键)
  const allKeys = document.querySelectorAll('[data-note]');
  allKeys.forEach(key => {
    key.setAttribute('data-note', 'C5');
    // 同步更新按键显示文本(可选)
    key.textContent = key.classList.contains('black-key') ? 'C#5' : 'C5';
  });
};

方式二:实现真正的八度移调(更符合合成器逻辑)

如果需求是将所有按键升高一个八度(而非全部改为C5),可以解析当前音符的音名和八度数值,进行递增:

function OctaveShift(){
  const allKeys = document.querySelectorAll('[data-note]');
  allKeys.forEach(key => {
    const currentNote = key.dataset.note;
    // 匹配音名(含#)和八度数字
    const noteMatch = currentNote.match(/([A-G#]+)(\d+)/);
    if(noteMatch){
      const noteName = noteMatch[1];
      const octave = parseInt(noteMatch[2]) + 1; // 升一个八度
      const newNote = `${noteName}${octave}`;
      key.setAttribute('data-note', newNote);
      // 同步更新显示文本
      key.textContent = newNote;
    }
  });
};

2. 额外修复:合成器3的波形切换函数错误

你代码中Sin3、Square3等函数错误操作了synth2,应改为synth3:

function Sin3(){
synth3.oscillator.type= 'sine';
console.log(synth3);
}
function Square3(){
synth3.oscillator.type= 'square';
console.log(synth3);
}
function Triangle3(){
synth3.oscillator.type= 'triangle';
console.log(synth3);
}
function Sawtooth3(){
synth3.oscillator.type= 'sawtooth';
console.log(synth3)
}

效果验证

修改后点击OctaveShift按钮,所有按键的data-note属性会被正确更新,此时点击钢琴键就能触发对应音高的声音。

内容的提问来源于stack exchange,提问作者A lvl 86 Lemon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 04:45:32