完整範例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>頁面跳轉倒計時</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.countdown { color: red; font-weight: bold; font-size: 1.2em; }
</style>
</head>
<body>
<p>歡迎訪問本站!</p>
<p>頁面將在 <span id="countdown" class="countdown">5</span> 秒後自動跳轉...</p>
<script>
$(function () {
var seconds = 5;
var $counter = $('#countdown');
var timer = setInterval(function () {
seconds--;
$counter.text(seconds);
if (seconds <= 0) {
clearInterval(timer);
window.location.href = 'https://www.example.com';
}
}, 1000);
});
</script>
</body>
</html>
核心邏輯解析
- 使用
setInterval 每秒遞減計數器,更新 DOM 顯示。
- 計數歸零時
clearInterval 停止定時器,執行 window.location.href 跳轉。
- 若需支援取消跳轉,可加入按鈕呼叫
clearInterval(timer)。
進階擴展
可配置化版本
function startCountdown(targetUrl, seconds, selector) {
var $el = $(selector);
var timer = setInterval(() => {
$el.text(--seconds);
if (seconds <= 0) {
clearInterval(timer);
location.href = targetUrl;
}
}, 1000);
}
// 使用:startCountdown('/home', 10, '#myCounter');
支援暫停/繼續
var timer, remaining = 5;
function start() { timer = setInterval(tick, 1000); }
function pause() { clearInterval(timer); }
function tick() { $('#c').text(--remaining); if (remaining <= 0) { clearInterval(timer); location.href = '/'; } }
注意事項
- 確保引入 jQuery,或改用原生
document.getElementById 移除依賴。
- 若頁面含表單未儲存資料,跳轉前應提示使用者(
beforeunload 事件)。
- SEO 場景建議使用 HTTP 302/301 重導向而非客戶端跳轉。