css部分
<style>
html,
body {
height: 100%;
}
body {
margin: 0;
background: url(./images/bg.jpg) left top/auto 100%;
}
ul {
padding: 0;
margin: 0;
list-style: none;
/* overflow: hidden; */
width: 832px;
margin: 0 auto;
}
ul>li {
width: 100px;
height: 400px;
border: 2px black solid;
float: left;
background-color: #fff;
text-align: center;
line-height: 30px;
box-shadow: 0 0 10px 5px black;
}
ul>li.active {
box-shadow: none;
}
/* 给除了最后一个li的其他li都加上after伪元素 */
ul>li:not(:last-child)::after {
display: block;
content: "";
width: 50px;
height: 200px;
background-color: black;
transform: translate(77px, -32px);
border-radius: 0 0 5px 5px;
}
div {
width: 800px;
height: 600px;
font-size: 0;
position: absolute;
left: 50%;
transform: translate(-50%);
overflow: hidden;
/* z-index: -1; */
}
div>img {
width: 100px;
transform: translateY(600px);
}
/* 音符移动的动画 */
@keyframes move {
from {
transform: translateY(600px);
opacity: 1;
}
to {
transform: translateY(0);
opacity: 0.1;
}
}
</style>
html部分
<body>
<ul>
<li>do</li>
<li>re</li>
<li>mi</li>
<li>fa</li>
<li>sol</li>
<li>la</li>
<li>si</li>
<li>do</li>
</ul>
<div>
<img src="./images/do.png" alt="">
<img src="./images/re.png" alt="">
<img src="./images/mi.png" alt="">
<img src="./images/fa.png" alt="">
<img src="./images/sol.png" alt="">
<img src="./images/la.png" alt="">
<img src="./images/si.png" alt="">
<img src="./images/do.png" alt="">
</div>
</body>
js部分
<script>
//绑定键盘事件
document.addEventListener("keydown", function(e) {
var event = e || window.event; //获取event对象
if (e.keyCode == 65) { //a
play(0);
} else if (e.keyCode == 83) { //s
play(1);
} else if (e.keyCode == 68) { //d
play(2);
} else if (e.keyCode == 70) { //f
play(3);
} else if (e.keyCode == 74) { //j
play(4);
} else if (e.keyCode == 75) { //k
play(5);
} else if (e.keyCode == 76) { //l
play(6);
} else if (e.keyCode == 186) { //;
play(7);
}
});
//绑定点击事件
var lis = document.querySelectorAll("ul>li");
for (var i = 0; i < lis.length; i++) {
lis[i].index = i;
lis[i].addEventListener("click", function() {
play(this.index);
})
}
function play(index) { //index:按键索引
var music = ["1.mp3", "2.mp3", "3.mp3", "4.mp3", "5.mp3", "6.mp3", "7.mp3", "8.mp3"];
//播放音乐
var audio = document.createElement("audio");
audio.src = "./mp3/" + music[index];
audio.play(); //播放
//移除琴键的阴影效果
document.querySelectorAll("ul>li")[index].classList.add("active");
//添加阴影效果
setTimeout(function() {
document.querySelectorAll("ul>li")[index].classList.remove("active");
}, 100);
//音符效果
document.querySelectorAll("div>img")[index].style.animation = "move 1s";
setTimeout(function() {
document.querySelectorAll("div>img")[index].style.animation = null;
}, 1000);
}
</script>