萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實作倒數計時器:分鐘秒雙顯示、啟動/暫停控制

網頁倒數計時器:預設 1 分 40 秒,點擊按鈕啟動/暫停,歸零自動停止。適用於限時搶購、考試計時、活動倒數等場景。

核心邏輯

  • 將「分:秒」轉為總秒數
  • 每秒遞減,重新拆解為分、秒並更新顯示
  • 按鈕切換 `setInterval` / `clearInterval`

完整範例(現代化重寫)

<!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>

擴充建議

  • 支援時/分/秒三段式、自訂初始時間輸入
  • 結束時觸發回調(播放聲音、彈窗、送出表單)
  • 使用 `performance.now()` 校準漂移,長時間運行更精準
  • 儲存狀態至 `localStorage`,頁面重整不歸零
  • 無障礙:`aria-live="assertive"` 播報剩餘時間
copyright © 萬盛學電腦網 all rights reserved