思路: 图片设置宽900px,找到鼠标按下时的x坐标和img距离body的x坐标,两个值相减,然后除100取整,赋值给a,通过判断a的值来确定放出那个音乐。
完整代码:
<!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;}img {width: 900px;}#box {margin: 100px auto;width: 900px;position: relative;}</style>
</head><body><div id="box">//将图片路径替换成自己的<img src="./keys.png" alt=""></div><script>var img = document.querySelector('img');var box = document.querySelector('#box');console.log(box, img);img.onmousedown = function (e) {var x = e.pageX - box.offsetLeft;console.log(x);var a = parseInt(x / 100);console.log(a);//将mp3路径替换成自己的文件switch (a) {case 0:var audio = new Audio('./钢琴9键-mp3/d1.mp3');audio.play();break;case 1:var audio = new Audio('./钢琴9键-mp3/d2.mp3');audio.play();break;case 2:var audio = new Audio('./钢琴9键-mp3/d3.mp3');audio.play();break;case 3:var audio = new Audio('./钢琴9键-mp3/d4.mp3');audio.play();break;case 4:var audio = new Audio('./钢琴9键-mp3/d5.mp3');audio.play();break;case 5:var audio = new Audio('./钢琴9键-mp3/d6.mp3');audio.play();break;case 6:var audio = new Audio('./钢琴9键-mp3/d7.mp3');audio.play();break;case 7:var audio = new Audio('./钢琴9键-mp3/d8.mp3');audio.play();break;case 8:var audio = new Audio('./钢琴9键-mp3/d9.mp3');audio.play();break;}}</script>
</body></html>
页面效果: