錯誤頁面、下載完成頁、驗證成功頁等,提示使用者 N 秒後自動導向首頁或指定頁面。
<!DOCTYPE html>
<html>
<head>
<title>系統錯誤 - 即將跳轉</title>
<link rel="stylesheet" href="css/login1.css" />
<script type="text/javascript">
var countdown = 5; // 倒數秒數
var timerId;
window.onload = function() {
timerId = setInterval(updateCountdown, 1000);
};
function updateCountdown() {
if (countdown === 0) {
clearInterval(timerId);
window.location.href = '../index.html'; // 跳轉目標
return;
}
document.getElementById('mes').innerHTML = countdown;
countdown--;
}
</script>
</head>
<body>
<div id="errorfrm">
<h3>出錯啦~~~</h3>
<div id="error">
<img src="images/error.gif" alt="錯誤圖示" />
<p>系統發生錯誤,請聯繫管理員!</p>
<p>將在 <span id="mes">5</span> 秒後自動返回首頁!</p>
</div>
</div>
</body>
</html>
setInterval(fn, 1000):每秒執行一次更新倒數顯示。clearInterval(timerId):倒數歸零時清除定時器,避免記憶體洩漏。window.location.href = url:執行頁面跳轉。window.onload 確保 DOM 就緒後再啟動定時器。var CountdownRedirect = {
seconds: 10,
timer: null,
url: '/home',
$el: null,
start: function(selector, targetUrl, secs) {
this.$el = $(selector);
this.url = targetUrl;
this.seconds = secs || 10;
this.render();
this.timer = setInterval(() => this.tick(), 1000);
return this;
},
tick: function() {
this.seconds--;
this.$el.find('.countdown-num').text(this.seconds);
this.$el.find('.progress-bar').css('width', (this.seconds/this.initial*100) + '%');
if (this.seconds <= 0) this.redirect();
},
redirect: function() {
clearInterval(this.timer);
window.location.href = this.url;
},
pause: function() { clearInterval(this.timer); },
resume: function() { this.timer = setInterval(() => this.tick(), 1000); },
render: function() {
this.initial = this.seconds;
this.$el.html(`
<p>${this.seconds} 秒後自動跳轉... <span class="countdown-num">${this.seconds}</span></p>
<div class="progress"><div class="progress-bar"></div></div>
<button onclick="CountdownRedirect.pause()">暫停</button>
`);
}
};
// 使用
CountdownRedirect.start('#redirect-box', '/dashboard', 10);
基本版滿足簡單需求,進階版適合需使用者互動控制的場景。