我使用 Javascript 大约一个月了,正在尝试建造一架钢琴。我的音频使用 keydown 事件工作正常,但现在我试图让钢琴的特定键看起来像是被按下的,并且无法弄清楚这部分。
其他上下文:尽管音频正常工作,但我在控制台日志中收到错误“whiteKey.contains 不是函数”和“blackKey.contains 不是函数”
“白色”和“黑色”是类,也是我的白键和黑键的默认 CSS。
“white-pushed”和“black-pushed”也是具有新 CSS 的类,激活时类似于按下的键。
谢谢,
const whiteKey = document.getElementsByClassName('white');
const blackKey = document.getElementsByClassName('black');
function whiteKeyDown(){
if (!whiteKey.contains('white-pushed')){
whiteKey.add('white-pushed')
}
}
function blackKeyDown(){
if (!blackKey.contains('black-pushed')){
blackKey.add('black-pushed')
}
}
document.addEventListener('keydown', (playNote) => {
if(playNote.repeat) return;
if(playNote.key == 'c'){
if (playNote.ctrlKey){
blackKeyDown(document.getElementById('low-c#').play())
} else {
whiteKeyDown(document.getElementById('low-c').play())
}
}
}
document.getElementsByClassName()
返回包含指定类名的元素数组
不能直接使用
.contains
,必须从 document.getElementsByClassName()
返回的数组中获取特定元素
例如:
const whiteKey = document.getElementsByClassName('white');
function whiteKeyDown(){
// whiteKey[0] is the first element that have the 'white' class name on it
if (!whiteKey[0].classList.contains('white-pushed')) {
whiteKey[0].classList.add('white-pushed')
}
}
您可以阅读有关该方法的更多信息这里