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

HTML5 + CSS3 + JS 實現背景音樂播放開關控制完整案例

     編輯:程式設計疑難解答

效果演示

頁面載入顯示精美的 ON/OFF 切換開關,點擊切換控制背景音樂播放/暫停,開關動畫流暢,純前端實現。

核心技術點

  • CSS3 動畫開關:利用 :checked 偽類驅動滑塊位移與陰影變化,無需 JS 控制樣式;
  • 音頻控制:使用 <bgsound> (IE 專用) 或 <audio> 標籤,JS 切換 src 屬性實現播放/停止;
  • 事件綁定:Checkbox onclick 觸發控制函數。

完整代碼 (單文件可運行)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>背景音樂開關</title>
<style>
/* 此處省略原始長 CSS,關鍵結構: */
.button { position: relative; width: 240px; height: 80px; 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; }
.button span:nth-of-type(2) { left: 4px; width: 116px; height: 72px; background: #c0392b; 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: #2ecc71; 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>
<bgsound id="bgm" src="">
<script>
function toggleBgm() {
    var bgm = document.getElementById('bgm');
    if (bgm.src === '') {
        bgm.src = './mp3/TheDawn.mp3';  // 請替換為實際音樂路徑
    } else {
        bgm.src = '';
    }
}
</script>
<label class="button">
    <input type="checkbox" onclick="toggleBgm()">
    <span></span><span></span><span></span>
</label>
</body>
</html>

現代化改進建議

  1. 替換 <bgsound> 為標準 <audio id="bgm" loop></audio>,JS 控制 play()/pause(),兼容所有瀏覽器;
  2. 添加 autoplay 策略應對:用戶首次交互後才允許自動播放,可在 onclick 中調用 audio.play().catch();
  3. 使用 localStorage 記住用戶偏好,頁面重載恢復狀態;
  4. 開關組件封裝為 Web Component (<music-toggle>) 復用。

總結

純 CSS3 實現開關動畫,JS 僅負責音頻 src 切換,結構清晰、零依賴、易維護。生產環境建議升級為 <audio> + 狀態持久化。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved