萬盛學電腦網

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

JavaScript 倒數計時並自動跳轉網址

基本倒數跳轉

function countdownRedirect(seconds, url) {
    var timer = setInterval(function(){
        seconds--;
        document.getElementById('countdown').textContent = seconds;
        if (seconds <= 0) {
            clearInterval(timer);
            location.href = url; // 必須加雙引號
        }
    }, 1000);
}
// 使用
countdownRedirect(5, 'https://www.example.com');

HTML

<span id="countdown">5</span> 秒後自動跳轉...

進階:支援暫停/繼續、顯示分秒

function formatTime(s) {
    var m = Math.floor(s/60), sec = s%60;
    return (m<10?'0':'')+m+':'+(sec<10?'0':'')+sec;
}

var timer, remaining;
function startCountdown(sec, url) {
    remaining = sec;
    $('#countdown').text(formatTime(remaining));
    timer = setInterval(function(){
        remaining--;
        $('#countdown').text(formatTime(remaining));
        if (remaining <= 0) { clearInterval(timer); location.href = url; }
    }, 1000);
}
$('#pauseBtn').click(function(){ clearInterval(timer); });
$('#resumeBtn').click(function(){ startCountdown(remaining, targetUrl); });

注意

  • location.href 必須為完整 URL 字串(含 https://)。
  • 若在 beforeunload 確認離開,使用者可能取消跳轉。
  • SEO 與使用者體驗考量:重要頁面避免自動跳轉,改用連結引導。
copyright © 萬盛學電腦網 all rights reserved