網頁倒數計時器:預設 1 分 40 秒,點擊按鈕啟動/暫停,歸零自動停止。適用於限時搶購、考試計時、活動倒數等場景。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>倒數計時器</title>
<style>
body { font-family:sans-serif; display:flex; flex-direction:column; align-items:center; justify-content:center; height:100vh; background:#1a1a1a; color:#fff; margin:0; }
#countdown { text-align:center; background:#222; padding:2rem; border-radius:12px; box-shadow:0 8px 30px rgba(0,0,0,0.5); }
.time { display:flex; justify-content:center; gap:0.5rem; margin-bottom:1.5rem; }
.time span { width:60px; line-height:2; background:#fbfbfb; color:#000; border:2px solid #b4b4b4; border-radius:6px; font-family:'Consolas',monospace; font-size:1.5rem; }
.time .label { background:none; border:none; color:#aaa; width:auto; font-family:inherit; font-size:1rem; }
button { border:none; width:200px; height:56px; background:#e74c3c; color:#fff; font-size:1.1rem; border-radius:8px; cursor:pointer; transition:background 0.2s; }
button:hover { background:#c0392b; }
button.paused { background:#27ae60; }
button.paused:hover { background:#219653; }
</style>
</head>
<body>
<div id="countdown">
<div class="time">
<span id="mm">01</span><span class="label">分</span>
<span id="ss">40</span><span class="label">秒</span>
</div>
<button id="btn">啟動</button>
</div>
<script>
(function() {
var $mm = document.getElementById('mm');
var $ss = document.getElementById('ss');
var $btn = document.getElementById('btn');
var timer = null;
var totalSeconds = 100; // 1分40秒
function pad(n) { return (n < 10 ? '0' : '') + n; }
function render() {
var m = Math.floor(totalSeconds / 60);
var s = totalSeconds % 60;
$mm.textContent = pad(m);
$ss.textContent = pad(s);
}
function tick() {
if (totalSeconds <= 0) {
clearInterval(timer);
timer = null;
$btn.textContent = '啟動';
$btn.classList.remove('paused');
return;
}
totalSeconds--;
render();
}
$btn.addEventListener('click', function() {
if (timer) {
clearInterval(timer);
timer = null;
$btn.textContent = '啟動';
$btn.classList.remove('paused');
} else {
timer = setInterval(tick, 1000);
$btn.textContent = '暫停';
$btn.classList.add('paused');
}
});
render();
})();
</script>
</body>
</html>