「3 秒後自動返回上一頁」是很常見的小需求,例如操作成功後的提示頁。用 setInterval 搭配定時遞減就能做到,但實作時有幾個容易忽略的細節。
<span id="totalSecond">3</span> 秒後自動返回
<script type="text/javascript">
var second = document.getElementById('totalSecond').textContent;
if (navigator.appName.indexOf("Explorer") > -1) {
// IE 用 innerText
second = document.getElementById('totalSecond').innerText;
} else {
// 其他瀏覽器用 textContent
second = document.getElementById('totalSecond').textContent;
}
setInterval("redirect()", 1000); // 每 1 秒呼叫一次
function redirect() {
if (second < 0) {
location.href = 'https://www.baidu.com';
} else {
if (navigator.appName.indexOf("Explorer") > -1) {
document.getElementById('totalSecond').innerText = second--;
} else {
document.getElementById('totalSecond').textContent = second--;
}
}
}
</script>
'innerText' in element 這類功能偵測。textContent 取回來是字串,second-- 雖然會自動轉型,但比較時容易出錯,應明確 parseInt。if (second <= 0),要嘛從 2 開始。<p>
<span id="totalSecond">3</span> 秒後自動返回
<a href="/index.html">立即返回</a>
</p>
<script>
(function () {
var el = document.getElementById('totalSecond');
var target = '/index.html';
var second = parseInt(el.textContent, 10) || 0;
var timer = setInterval(function () {
second--;
if (second <= 0) {
clearInterval(timer); // 記得清除
location.href = target;
return;
}
el.textContent = second;
}, 1000);
})();
</script>
location.replace(target); // 使用者按後退不會回到這個倒數頁
document.addEventListener('visibilitychange', function () {
if (document.hidden) { clearInterval(timer); }
});
history.back() 在沒有歷史紀錄時(例如使用者直接開啟這個連結)會無效,實務上建議導向一個明確的頁面。若只是單純轉址、不需要倒數提示,用 meta 標籤更簡潔,且不需要 JavaScript:
<meta http-equiv="refresh" content="3;url=/index.html" />
不過同樣地,這方式無法被使用者中止,無障礙上仍不如提供一個明確的「繼續」按鈕來得友善。