js 一個按鈕控制背景音樂的開關
阿新 • • 發佈:2020-08-03
css部分
1 <style> 2 3 .open { 4 width: 50px; 5 height: 50px; 6 background: #fff url(https://images.cnblogs.com/cnblogs_com/jiong-ling/1818899/t_2008021215371.png) no-repeat; 7 opacity: 0.6; 8 display: block; 9 background-size: 100% 100%; 10 position:fixed; 11 top: 20px; 12 right: 20px; 13 border-radius: 50%; 14 } 15 16 .close { 17 width: 50px; 18 height: 50px; 19 background: #fff url(https://images.cnblogs.com/cnblogs_com/jiong-ling/1818899/t_2008021215371.png) no-repeat;20 opacity: 0.6; 21 display: block; 22 background-size: 100% 100%; 23 right: 20px; 24 top: 20px; 25 position:fixed; 26 border-radius: 50%; 27 } 28 </style>
js部分
其實就是利用了jQuery
觸發了點選函式後進行if判斷 然後呼叫.play() .pause() 根據播放狀態分別新增刪除close類 和open類
1 <script src="jquery.js"></script> 2 <script> 3 var music = document.getElementById("bgMusic"); 4 $("#audioBtn").click(function () { 5 if (music.paused) { 6 music.play(); 7 $("#audioBtn").removeClass("close").addClass("open"); 8 } else { 9 music.pause(); 10 $("#audioBtn").removeClass("open").addClass("close"); 11 } 12 }); 13 </script>
html
autoplay自動播放 谷歌好像不能用 但是部落格園上可以用^-^
1 <a class="close" id="audioBtn" style="cursor:pointer;"></a> 2 <audio id="bgMusic" src="https://files.cnblogs.com/files/jiong-ling/%E7%8E%AB%E7%91%B0%E8%8A%B1%E7%9A%84%E8%91%AC%E7%A4%BC.css" autoplay="autoplay" loop="loop"></audio>
全部程式碼
<!DOCTYPEhtml> <htmllang="en"><head> <metacharset="UTF-8"> <metaname="viewport"content="width=device-width,initial-scale=1.0"> <title>Document</title> <style> .open{ width:50px; height:50px; background:#fffurl(https://images.cnblogs.com/cnblogs_com/jiong-ling/1818899/t_2008021215371.png)no-repeat; display:block; background-size:100%100%; position:fixed; top:20px; right:20px; border-radius:50%; opacity:0.6; }
.close{ width:50px; height:50px; background:#fffurl(https://images.cnblogs.com/cnblogs_com/jiong-ling/1818899/t_2008021215422.png)no-repeat; display:block; background-size:100%100%; position:fixed; top:20px; right:20px; border-radius:50%; opacity:0.6; } </style> </head>
<body> <aclass="close"id="audioBtn"style="cursor:pointer;"></a> <audioid="bgMusic"src="https://files.cnblogs.com/files/jiong-ling/%E7%8E%AB%E7%91%B0%E8%8A%B1%E7%9A%84%E8%91%AC%E7%A4%BC.css"autoplay="autoplay"loop="loop"></audio> </body> <scriptsrc="jquery.js"></script> <script> varmusic=document.getElementById("bgMusic"); $("#audioBtn").click(function(){ if(music.paused){ music.play(); $("#audioBtn").removeClass("close").addClass("open"); }else{ music.pause(); $("#audioBtn").removeClass("open").addClass("close"); } }); </script>
</html>