我实现了一个名为
showPianoProdigyOverlay()
的 JavaScript 函数,旨在显示虚拟钢琴的叠加层。单击钢琴上的每个键都会触发相应的音频文件。然而,尽管看似正确的实现,音频播放却无法按预期工作。问题在于 playNote()
中的 showPianoProdigyOverlay()
函数。尽管正确记录了单击的键的数据注释属性,但检索相应音频元素的 getElementById()
调用始终返回 null。即使在彻底的调试尝试之后,这个问题仍然存在,让我对根本原因感到困惑。任何有关解决此问题的见解或建议将不胜感激!
function showPianoProdigyOverlay() {
characterSpeed = 0;
inOverlay = true;
const overlay = document.createElement('div');
overlay.className = 'overlay';
overlay.innerHTML = `
<div class="overlay-content">
<div class="piano">
<div data-note="C" class="key w"></div>
<div data-note="Db" class="key b"></div>
<div data-note="D" class="key w"></div>
<div data-note="Eb" class="key b"></div>
<div data-note="E" class="key w"></div>
<div data-note="F" class="key w"></div>
<div data-note="Gb" class="key b"></div>
<div data-note="G" class="key w"></div>
<div data-note="Ab" class="key b"></div>
<div data-note="A" class="key w"></div>
<div data-note="Bb" class="key b"></div>
<div data-note="B" class="key w"></div>
</div>
<audio id="C" src="notes/C.mp3'></audio>
<audio id="Db" src="notes/Db.mp3'></audio>
<audio id="D" src="notes/D.mp3'></audio>
<audio id="Eb" src="notes/Eb.mp3'></audio>
<audio id="E" src="notes/E.mp3'></audio>
<audio id="F" src="notes/F.mp3'></audio>
<audio id="Gb" src="notes/Gb.mp3'></audio>
<audio id="G" src="notes/G.mp3'></audio>
<audio id="Ab" src="notes/Ab.mp3'></audio>
<audio id="A" src="notes/A.mp3'></audio>
<audio id="Bb" src="notes/Bb.mp3'></audio>
<audio id="B" src="notes/B.mp3'></audio>
</div>
`;
document.body.appendChild(overlay);
const styleElement = document.createElement('style');
styleElement.textContent = `
*, *::before, *::after{
box-sizing: border-box;
}
.overlay {
display: flex;
justify-content: center;
align-items: center;
}
.piano {
display: flex;
}
.key {
height: calc(var(--width) * 4);
width: var(--width);
}
.w {
--width: 100px;
background-color: white;
border: 1px solid #333;
}
.b {
--width: 60px;
background-color: black;
border: 1px solid #333;
margin-left: calc(var(--width) / -2);
margin-right: calc(var(--width) / -2);
z-index: 2;
}
`;
document.head.appendChild(styleElement);
const keys = document.querySelectorAll('.key');
console.log(keys);
keys.forEach(key => {
key.addEventListener('click', () => playNote(key))
})
function playNote(key){
console.log("Note:", key.dataset.note);
const noteAudio = document.getElementById(key.dataset.note)
console.log("Audio element:", noteAudio);
noteAudio.play()
}
}
我尝试通过记录相关变量(例如单击的键的数据注释属性和使用
playNote()
检索的音频元素)来调试 showPianoProdigyOverlay()
中的 getElementById()
函数。我希望根据 data-note 属性正确检索音频元素。然而,尽管记录了正确的数据注释值,getElementById()
调用始终为相应的音频元素返回 null。
您使用哪个编辑器?您有一个格式错误的 HTML 块:
<audio id="C" src="notes/C.mp3'></audio> [...]
"
关闭第一个
'
<audio id="C" src="notes/C.mp3"></audio>
等