本片文章通过触发键盘事件来触发对应的音乐,而且给页面添加了渐变的active类名,通过触发不同的鼠标事件,然后active类移动来实现按下钢琴键的视觉效果。
关键代码:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>* {margin: 0;padding: 0;list-style: none;}#box {margin: 100px auto;width: 900px;height: 500px;position: relative;background: url(./keys.png) no-repeat;background-size: contain;}li {width: 100px;height: 440px;float: left;}.active {background: linear-gradient(to bottom, #ffffff, #333);opacity: 0.5;}</style>
</head><body><div id="box"><ul><li class="active"></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li></ul></div><script>// 思路:给li遍历上键盘事件,每个不同的li触发不同的音乐,再通过css添加上渐隐的效果。var lis = document.querySelectorAll('li');var box = document.querySelector('#box');// console.log(box, lis);document.addEventListener('keydown', function (e) {e = e || window.event;var k = e.key;if (k >= '1' && k <= '9') {var audio = new Audio(`./钢琴9键-mp3/d${k}.mp3`);audio.play();for (var i = 0; i < lis.length; i++) {lis[i].classList.remove('active');}lis[k - 1].classList.add('active');}})</script>
</body></html>
页面效果: