[英]How can I make first button on this JavaScript piano working?
我已经根据 yt 教程制作了钢琴,但我有一些无法解决的问题......当我在第一个按钮上使用鼠标/键盘单击时,它不起作用,其他人工作得很好。 你知道这段代码的错误在哪里吗?
const WHITE_KEYS = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p']
const BLACK_KEYS = ['2', '3', '5', '6', '7', '9', '0']
const keys = document.querySelectorAll('.key')
const whiteKeys = document.querySelectorAll('.key.white')
const blackKeys = document.querySelectorAll('.key.black')
keys.forEach(key => {
key.addEventListener('click', () => playNote(key))
})
document.addEventListener('keydown', e => {
if (e.repeat) return
const key = e.key
const whiteKeyIndex = WHITE_KEYS.indexOf(key)
const blackKeyIndex = BLACK_KEYS.indexOf(key)
if (whiteKeyIndex > -2) playNote(whiteKeys[whiteKeyIndex])
if (blackKeyIndex > -1) playNote(blackKeys[blackKeyIndex])
})
function playNote(key) {
const noteAudio = document.getElementById(key.dataset.note)
noteAudio.currentTime = 0
noteAudio.play()
key.classList.add('active')
noteAudio.addEventListener('ended', () => {
key.classList.remove('active')
})
}
它在您的 html 中-您缺少“c4”
改变
<audio id="C" ><source src="notes/C4.mp3"></audio>
到
<audio id="C4" ><source src="notes/C4.mp3"></audio>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.