<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style></style> </head> <body> <h1>Audio music</h1> <audio id="bgMusic" src="res/bg2.mp3" autoplay > 浏览器不支持Audio标签 </audio> <label> <input id="bgSwitch" type="checkbox" checked> 是否播放背景音乐 </label> <script> // console.log("test"); // bgSwitch.onchange = function(){ // console.log("onchange"); // if(this.checked){ // bgMusic.play(); // }else{ // bgMusic.pause(); // } // } bgSwitch.onchange = function(){ var v = bgMusic.volume; if(this.checked){ bgMusic.volume = 0; v = 0; bgMusic.play(); console.log("play"); var t = setInterval(function(){ v+= 0.1; console.log('v1'+v); if(v<=1){ bgMusic.volume = v; }else{ clearInterval(t); } },200); }else{ var t = setInterval(function(){ v-=0.1; console.log('v2'+v); if(v>0){ bgMusic.volume = v; }else{ clearInterval(t); bgMusic.pause(); console.log("pause"); } },200); } } </script> </body> </html>