頁面加載顯示精美 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 重置進度,符合「開關」語義。localStorage.setItem('musicOn', bgm.paused ? '0' : '1') 持久化狀態;<input type="range" min="0" max="1" step="0.1" oninput="bgm.volume=this.value">;class MusicToggle extends HTMLElement 自定義元素復用。