首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 搭配 JavaScript 實作倒數計時自動跳轉頁面

     編輯:關於ASP.NET

在 ASP.NET 網頁中實作「N 秒後自動跳轉」功能,核心邏輯完全在前端 JavaScript 執行,後端僅負責輸出初始秒數與目標網址。本文提供完整可執行範例,包含倒數顯示、立即跳轉連結、取消跳轉等實用功能,並說明避免常見坑點的最佳寫法。

完整可執行範例

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AutoRedirect.aspx.cs" Inherits="AutoRedirect" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
    <title>頁面自動跳轉示範</title>
    <script type="text/javascript">
        var countdown = 5; // 倒數秒數
        var targetUrl = "https://www.google.com"; // 目標網址
        var timerId = null;

        window.onload = function startCountdown() {
            updateDisplay();
            timerId = setInterval(function () {
                countdown--;
                updateDisplay();
                if (countdown <= 0) {
                    clearInterval(timerId);
                    // 使用 replace 避免留在瀏覽器歷史記錄中
                    location.replace(targetUrl);
                }
            }, 1000);
        };

        function updateDisplay() {
            var el = document.getElementById("countdownDisplay");
            if (el) el.innerText = countdown;
        }

        // 使用者點擊「取消跳轉」或「立即跳轉」
        function cancelRedirect() {
            clearInterval(timerId);
            document.getElementById("redirectPanel").innerHTML = "已取消自動跳轉。";
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div id="redirectPanel" style="text-align:center; padding:50px; font-size:18px;">
            歡迎光臨,頁面將在 
            <span id="countdownDisplay" style="color:red; font-weight:bold;">5</span> 
            秒後自動跳轉至 
            <a href="https://www.google.com" target="_blank">Google</a>
            <br /><br />
            <a href="https://www.google.com" style="color:#ff00ff;">立即跳轉 >></a> 
            | 
            <a href="javascript:cancelRedirect();" style="color:blue;">取消跳轉</a>
        </div>
    </form>
</body>
</html>

關鍵技術細節解析

1. 使用 setInterval 而非遞迴 setTimeout

// ✅ 推薦:setInterval 固定間隔,易於清除
var timerId = setInterval(function() { ... }, 1000);
clearInterval(timerId); // 精確停止

// ❌ 不推薦:遞迴 setTimeout 難以管理
function tick() { 
    setTimeout(tick, 1000); 
}
// 無法輕易中途取消

2. location.replace() vs location.href

方法行為適用場景
location.replace(url)替換歷史記錄,無法按「上一頁」返回自動跳轉、登入後導向、錯誤頁導向
location.href = url新增歷史記錄,可按「上一頁」返回使用者主動點擊連結、表單送出

3. 後端動態傳遞參數

// AutoRedirect.aspx.cs
public partial class AutoRedirect : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // 從 QueryString 或資料庫取得動態值
        int seconds = 5;
        string url = "https://www.google.com";
        
        if (!string.IsNullOrEmpty(Request.QueryString["t"]))
            int.TryParse(Request.QueryString["t"], out seconds);
        if (!string.IsNullOrEmpty(Request.QueryString["u"]))
            url = Request.QueryString["u"];

        // 註冊啟動腳本,傳遞參數給 JS
        string script = string.Format(
            "var countdown = {0}; var targetUrl = '{1}'; startCountdown();",
            seconds, url.Replace("'", "\\'") // 防止單引號注入
        );
        ClientScript.RegisterStartupScript(this.GetType(), "autoRedirect", script, true);
    }
}

進階功能擴充

頁面可見性 API:分頁切換時暫停倒數

var hiddenProp = 'hidden' in document ? 'hidden' : 
                 'webkitHidden' in document ? 'webkitHidden' : 
                 'mozHidden' in document ? 'mozHidden' : null;

if (hiddenProp) {
    var visibilityChange = hiddenProp.replace(/hidden/i, 'visibilitychange');
    document.addEventListener(visibilityChange, function() {
        if (document[hiddenProp]) {
            // 分頁隱藏:暫停倒數
            clearInterval(timerId);
        } else {
            // 分頁顯示:恢復倒數
            timerId = setInterval(tick, 1000);
        }
    });
}

倒數進度條視覺化

<div style="width:300px; height:20px; background:#eee; border-radius:10px; overflow:hidden;">
    <div id="progressBar" style="width:100%; height:100%; background:linear-gradient(90deg, #4caf50, #8bc34a); transition:width 1s linear;"></div>
</div>

<script>
function updateDisplay() {
    document.getElementById("countdownDisplay").innerText = countdown;
    var percent = (countdown / initialCountdown) * 100;
    document.getElementById("progressBar").style.width = percent + "%";
}
</script>

常見應用場景

場景倒數秒數目標頁面備註
登入成功導向3-5 秒會員中心/原請求頁顯示歡迎訊息
付款完成導向5-10 秒訂單明細/下載頁確認交易狀態
錯誤/維護頁面10-30 秒首頁/服務狀態頁提供人工連結
舊網址永久轉址0-3 秒新網址SEO 301 導向優先,JS 為備援
廣告/活動頁面5-15 秒活動詳情/商品頁配合進度條、取消鈕

安全性與無障礙注意事項

  1. 提供取消機制:WCAG 2.2.1 要求使用者可暫停/停止/隱藏自動更新內容
  2. 語意化標記:使用 <span id="countdownDisplay" aria-live="polite"> 讓螢幕閱讀器宣讀倒數
  3. 防止開放式重導向:後端驗證目標網址屬於允許清單(同網域或信任網域),避免釣魚攻擊
  4. 無腳本備援:<noscript><meta http-equiv="refresh" content="5;url=..." /></noscript>

JavaScript 倒數跳轉是提升使用者體驗的常用技巧,關鍵在於:穩定的計時器管理、正確的導向方式、動態參數傳遞、以及符合無障礙規範的使用者控制權。掌握上述模式,即可輕鬆應用於各種導向場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved