需求:使用者完成操作後,停留 2 秒顯示提示,再自動導向目標頁面。本文提供兩種主流做法與注意事項。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>跳轉中...</title>
<!-- 2 秒後跳轉到指定 URL -->
<meta http-equiv="refresh" content="2; url=https://example.com/target">
<style>
body { font-family: sans-serif; text-align: center; padding-top: 50px; }
.countdown { color: #e53935; font-weight: bold; }
</style>
</head>
<body>
<p>操作成功!<span class="countdown" id="sec">2</span> 秒後自動跳轉...</p>
<p><a href="https://example.com/target">若未自動跳轉,請點這裡</a></p>
<script>
// 選配:倒數計時顯示增強體驗
let s = 2;
const el = document.getElementById('sec');
const timer = setInterval(() => {
s--; el.textContent = s;
if (s <= 0) clearInterval(timer);
}, 1000);
</script>
</body>
</html>
優點:無腳本依賴、最簡單。
缺點:無法在跳轉前執行邏輯(如儲存狀態),瀏覽器歷史記錄會保留此中介頁。
setTimeout(彈性高)<script>
// 2 秒後跳轉
setTimeout(() => {
// location.href 會在歷史記錄留下紀錄(可按「上一頁」回來)
// location.replace() 不留歷史,按「上一頁」會跳過此頁
window.location.replace('https://example.com/target');
}, 2000);
</script>
進階:結合倒數計時、確認對話框、AJAX 完成後再跳轉。
location.href 可回上一頁;location.replace() 不留痕跡,視需求選擇。http-equiv="refresh" 可能被阻擋,改用 JS 方式。<!-- 1. 標準 HTML5 -->
<meta http-equiv="refresh" content="3; url=/success">
<!-- 2. 配合 JS 倒數與手動連結 -->
<p>3 秒後跳轉 <a id="manual" href="/success">立即前往</a></p>
<script>
const link = document.getElementById('manual');
let t = 3;
const iv = setInterval(() => {
link.textContent = `${--t} 秒後跳轉`;
if (t <= 0) { clearInterval(iv); link.textContent = '立即前往'; }
}, 1000);
</script>
根據專案需求選擇:靜態簡單頁用 meta refresh,需邏輯控制用 JavaScript。