在 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>
// ✅ 推薦:setInterval 固定間隔,易於清除
var timerId = setInterval(function() { ... }, 1000);
clearInterval(timerId); // 精確停止
// ❌ 不推薦:遞迴 setTimeout 難以管理
function tick() {
setTimeout(tick, 1000);
}
// 無法輕易中途取消
| 方法 | 行為 | 適用場景 |
|---|---|---|
| location.replace(url) | 替換歷史記錄,無法按「上一頁」返回 | 自動跳轉、登入後導向、錯誤頁導向 |
| location.href = url | 新增歷史記錄,可按「上一頁」返回 | 使用者主動點擊連結、表單送出 |
// 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);
}
}
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 秒 | 活動詳情/商品頁 | 配合進度條、取消鈕 |
<span id="countdownDisplay" aria-live="polite"> 讓螢幕閱讀器宣讀倒數<noscript><meta http-equiv="refresh" content="5;url=..." /></noscript>JavaScript 倒數跳轉是提升使用者體驗的常用技巧,關鍵在於:穩定的計時器管理、正確的導向方式、動態參數傳遞、以及符合無障礙規範的使用者控制權。掌握上述模式,即可輕鬆應用於各種導向場景。