這個範例常被歸類在「選項卡切換」題目下,實際程式內容卻是另一個經典需求:頁面顯示剩餘秒數,倒數結束後自動導向別的網址,常見於 404 頁面或登出提示頁。
同一段文字,IE 用 innerText、Firefox 等瀏覽器用 textContent,兩邊都寫一遍最保險:
<span id="totalSecond">3</span>秒後自動返回
<script type="text/javascript">
var second;
if (navigator.appName.indexOf("Explorer") > -1) {
second = document.getElementById('totalSecond').innerText;
} else {
second = document.getElementById('totalSecond').textContent;
}
setInterval("redirect()", 1000); // 每秒呼叫一次
function redirect() {
if (second < 0) {
location.href = 'https://要跳轉的網站';
} else {
if (navigator.appName.indexOf("Explorer") > -1) {
document.getElementById('totalSecond').innerText = second--;
} else {
document.getElementById('totalSecond').textContent = second--;
}
}
}
</script>
用 navigator.appName 判斷瀏覽器已是上一個世代的做法,如今可靠的方式是偵測屬性是否存在,例如 'textContent' in el。另外 second 從字串取來後應先 parseInt,否則 second-- 雖會自動轉型,但邊界判斷容易出錯;把跳轉寫成 second <= 0 也比 < 0 更符合「倒數歸零即跳」的語意。