我已经创建了此钢琴键盘。它有声音,但是我无法在代码段中添加它。声音由每个键的onclick
属性触发,并通过js中的函数进行播放。我想验证用户是否按以下顺序按下具有以下ID的键:c c g g a a g,然后提示“成功!”。我能做的最短方法是什么?
#piano {
display: flex;
margin: 1em;
cursor: pointer;
}
.key {
border-radius: 4px;
}
.white {
height: 220px;
width: 50px;
background: white;
border: 1px solid black;
border-right: none;
z-index: 0;
}
.white:last-child {
border-right: 1px solid black;
}
.white:hover {
filter: brightness(90%);
}
.white:active {
filter: brightness(70%);
}
.black {
position: absolute;
height: 130px;
width: 31px;
background: black;
z-index: 1;
}
.black:hover {
background: #0f0f0f;
}
.black:active {
background: #0a0a0a;
}
#c-sharp {
margin-left: 36px;
}
#d-sharp {
margin-left: 87px;
}
#f-sharp {
margin-left: 189px;
}
#g-sharp {
margin-left: 240px;
}
#a-sharp {
margin-left: 291px;
}
<div id="piano">
<span class="white key" id="c"></span>
<span class="black key" id="c-sharp"></span>
<span class="white key" id="d"></span>
<span class="black key" id="d-sharp"></span>
<span class="white key" id="e"></span>
<span class="white key" id="f"></span>
<span class="black key" id="f-sharp"></span>
<span class="white key" id="g"></span>
<span class="black key" id="g-sharp"></span>
<span class="white key" id="a"></span>
<span class="black key" id="a-sharp"></span>
<span class="white key" id="b"></span>
</div>
我的方法如下所示:
向每个范围添加一个事件监听器,并在单击它时将其ID附加到一个名为pressed的字符串中。添加ID(例如'a')后,将其与指定的订单进行比较。
这应该以最简单的方式解决问题:)
let pressed = '';
document.querySelectorAll('span').forEach(item => {
item.addEventListener('click', event => {
pressed += item.id;
if( pressed == 'ccggaag' ) {
alert("Success");
} else {
console.log(pressed);
}
})
})
#piano {
display: flex;
margin: 1em;
cursor: pointer;
}
.key {
border-radius: 4px;
}
.white {
height: 220px;
width: 50px;
background: white;
border: 1px solid black;
border-right: none;
z-index: 0;
}
.white:last-child {
border-right: 1px solid black;
}
.white:hover {
filter: brightness(90%);
}
.white:active {
filter: brightness(70%);
}
.black {
position: absolute;
height: 130px;
width: 31px;
background: black;
z-index: 1;
}
.black:hover {
background: #0f0f0f;
}
.black:active {
background: #0a0a0a;
}
#c-sharp {
margin-left: 36px;
}
#d-sharp {
margin-left: 87px;
}
#f-sharp {
margin-left: 189px;
}
#g-sharp {
margin-left: 240px;
}
#a-sharp {
margin-left: 291px;
}
<div id="piano">
<span class="white key" id="c"></span>
<span class="black key" id="c-sharp"></span>
<span class="white key" id="d"></span>
<span class="black key" id="d-sharp"></span>
<span class="white key" id="e"></span>
<span class="white key" id="f"></span>
<span class="black key" id="f-sharp"></span>
<span class="white key" id="g"></span>
<span class="black key" id="g-sharp"></span>
<span class="white key" id="a"></span>
<span class="black key" id="a-sharp"></span>
<span class="white key" id="b"></span>
</div>