頁面載入顯示精美的 ON/OFF 切換開關,點擊切換控制背景音樂播放/暫停,開關動畫流暢,純前端實現。
:checked 偽類驅動滑塊位移與陰影變化,無需 JS 控制樣式;<bgsound> (IE 專用) 或 <audio> 標籤,JS 切換 src 屬性實現播放/停止;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>
<bgsound> 為標準 <audio id="bgm" loop></audio>,JS 控制 play()/pause(),兼容所有瀏覽器;autoplay 策略應對:用戶首次交互後才允許自動播放,可在 onclick 中調用 audio.play().catch();localStorage 記住用戶偏好,頁面重載恢復狀態;<music-toggle>) 復用。純 CSS3 實現開關動畫,JS 僅負責音頻 src 切換,結構清晰、零依賴、易維護。生產環境建議升級為 <audio> + 狀態持久化。