頁面定時跳轉(也稱倒數跳轉)在表單提交成功後、活動倒數等情境中相當常見。本文整理了幾種以JavaScript實作定時跳轉的寫法,供大家依需求選用。
以下程式碼需寫在body區域內:
<script type="text/javascript">
// 3秒鐘之後跳轉到指定的頁面
setTimeout("window.location.href = 'https://3aj.cn/javascript/19.html'", 3000);
</script>
在頁面的head區塊內加入以下程式碼:
<!-- 5秒鐘後跳轉到指定的頁面 --> <meta http-equiv="refresh" content="5;url=https://3aj.cn/javascript/19.html" />
這種寫法較為完整,常見於登入後的定時跳轉,並會即時顯示剩餘秒數:
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js定時跳轉頁面的方法</title>
</head>
<body>
<script type="text/javascript">
var t = 10; // 設定跳轉的時間
setInterval("refer()", 1000); // 啟動1秒定時
function refer(){
if (t == 0) {
location = "https://3aj.cn/javascript/19.html"; // 設定跳轉的鏈接地址
}
document.getElementById('show').innerHTML = "" + t + "秒後跳轉到php程序員教程網"; // 顯示倒計時
t--; // 計數器遞減
}
</script>
<span id="show"></span>
</body>
</html>
第一種以 setTimeout 最為簡潔;第二種用HTML的 meta refresh 完全不寫JS也能達成;第三種則搭配 setInterval 每秒更新倒數文字,使用者體驗最佳。可依實際需求挑選最合適的方案。