上一篇介紹了 HTML 頁面三秒後自動跳轉的三種常見做法,這篇再補充五個更完整的實例,涵蓋純 HTML、JavaScript 以及跨瀏覽器的相容處理。
這五個例子的功能一致:在 5 秒後自動跳轉到同目錄下的 hello.html(可依需求自行替換成你的目標網址)。
<head> <meta http-equiv="refresh" content="5;url=hello.html"> </head>
優點:極簡,一行搞定。
缺點:在 Struts Tiles 環境中無法使用。
<script language="javascript" type="text/javascript"><!--
setTimeout("javascript:location.href='https://liting6680.blog.163.com/blog/hello.html'", 5000);
// --></script>
優點:靈活,可以與其他功能結合。
缺點:不同瀏覽器之間可能存在差異。
<span id="totalSecond">5</span>
<script language="javascript" type="text/javascript"><!--
var second = totalSecond.innerText;
setInterval("redirect()", 1000);
function redirect(){
totalSecond.innerText = --second;
if(second < 0) location.href = 'https://liting6680.blog.163.com/blog/hello.html';
}
// --></script>
優點:有倒數提示,對使用者更友善。
缺點:Firefox 不支援(Firefox 不支援 span、div 等元素的 innerText 屬性)。
<script language="javascript" type="text/javascript"><!--
var second = document.getElementById('totalSecond').textContent;
setInterval("redirect()", 1000);
function redirect()
{
document.getElementById('totalSecond').textContent = --second;
if (second < 0) location.href = 'https://liting6680.blog.163.com/blog/hello.html';
}
// --></script>
差異在於 Firefox 用 textContent 取代 IE 的 innerText。
<span id="totalSecond">5</span>
<script language="javascript" type="text/javascript"><!--
if(navigator.appName.indexOf("Explorer") > -1){
document.getElementById('totalSecond').innerText = "my text innerText";
} else{
document.getElementById('totalSecond').textContent = "my text textContent";
}
// --></script>
把方法三與方法四整合起來,就是一份能同時在 IE 與 Firefox 上運作的倒數跳轉:
<span id="totalSecond">5</span>
<script language="javascript" 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://liting6680.blog.163.com/blog/hello.html';
}
else
{
if (navigator.appName.indexOf("Explorer") > -1)
{
document.getElementById('totalSecond').innerText = second--;
}
else
{
document.getElementById('totalSecond').textContent = second--;
}
}
}
// --></script>
如果只是要在某些場合做簡單轉址,方法一最省事;需要搭配其他邏輯時用方法二;如果希望讓使用者知道「還剩幾秒」,就用帶倒數的版本,並記得用方法五的偵測寫法把 innerText 與 textContent 的差異處理掉。實務上新專案也可以直接用 textContent,它已是標準屬性,IE 以外的瀏覽器都支援。