首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

HTML5 背景音樂開關控制完整實現代碼(含 CSS3 動畫開關)

     編輯:程式設計疑難解答

功能描述

頁面加載顯示精美 ON/OFF 切換開關,點擊控制背景音樂播放/停止,開關狀態與音樂同步。

完整可運行代碼

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>背景音樂開關</title>
<style>
/* CSS3 動畫開關樣式,見前文 25082 完整版 */
.button { display: block; position: absolute; width: 240px; height: 80px; top: 50%; left: 50%; transform: translate(-50%, -50%); border-radius: 40px; cursor: pointer; }
.button input { display: none; }
.button span:first-of-type { position: absolute; top: 4px; right: 4px; width: 160px; height: 72px; border-radius: 36px; transition: right .4s cubic-bezier(1,0,0,1); z-index: 100; background: linear-gradient(to bottom, #2c3e50, #1e2a36); }
.button span:nth-of-type(2) { left: 4px; width: 116px; height: 72px; background: linear-gradient(to bottom, #c0392b, #d65548); border-radius: 36px 0 0 36px; }
.button span:nth-of-type(2)::after { content: "OFF"; left: 18px; top: 26px; color: #fff; font: 800 24px/1 "Open Sans"; }
.button span:last-of-type { right: 4px; width: 116px; height: 72px; background: linear-gradient(to bottom, #2ecc71, #7ee2a8); border-radius: 0 36px 36px 0; opacity: .2; }
.button span:last-of-type::after { content: "ON"; right: 22px; top: 26px; color: #fff; font: 800 24px/1 "Open Sans"; }
.button input:checked ~ span:first-of-type { right: 76px; }
.button input:checked ~ span:nth-of-type(2) { opacity: .2; }
.button input:checked ~ span:last-of-type { opacity: 1; }
</style>
</head>
<body>
<audio id="bgm" loop><source src="./mp3/TheDawn.mp3" type="audio/mpeg"></audio>
<script>
const bgm = document.getElementById('bgm');
function toggleBgm() {
    if (bgm.paused) {
        bgm.play().catch(() => {});  // 自動播放策略捕獲
    } else {
        bgm.pause();
        bgm.currentTime = 0;
    }
}
</script>
<label class="button">
    <input type="checkbox" onclick="toggleBgm()">
    <span></span><span></span><span></span>
</label>
</body>
</html>

關鍵改進點

  • 使用標準 <audio> 替代 <bgsound>,支持全瀏覽器;
  • loop 屬性實現循環播放;
  • play().catch() 應對瀏覽器自動播放策略;
  • 暫停時 currentTime = 0 重置進度,符合「開關」語義。

擴展建議

  1. localStorage.setItem('musicOn', bgm.paused ? '0' : '1') 持久化狀態;
  2. 添加音量滑塊 <input type="range" min="0" max="1" step="0.1" oninput="bgm.volume=this.value">;
  3. 封裝為 class MusicToggle extends HTMLElement 自定義元素復用。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved