在某些場景下,需要網頁在指定的時間后,網頁能夠自動跳轉到指定頁面,比如在無法找到指定網頁的情況下,就會顯示之前設置好的404頁面,并且跳轉到指定的頁面,下面就是一段代碼實現了此效果。
代碼如下:
<!DOCTYPE html><html><head><meta charset=" utf-8"><meta name="author" content="http://m.survivalescaperooms.com/" /><title>js指定時間之后跳轉到指定頁面代碼實例</title> <script type="text/javascript">function redirect(){if(second<0){location.href='http://wm.survivalescaperooms.com';} else{if(navigator.appName.indexOf("Explorer")>-1){document.getElementById('totalSecond').innerText=second--;} else{document.getElementById('totalSecond').textContent=second--;}}}window.onload=function(){var second=document.getElementById('totalSecond').textContent;if(navigator.appName.indexOf("Explorer")>-1){second=document.getElementById('totalSecond').innerText;} else{second = document.getElementById('totalSecond').textContent;}setInterval("redirect()",1000);}</script></head><body><h1>找不到指定的頁面</h1><span id="totalSecond">3</span>秒后自動跳轉到指定頁面</body></html>以上代碼,可以在三秒之后跳轉到指定的頁面,下面簡單介紹一下實現過程。
一.實現原理:
使用定時器函數,每隔一秒修改一次span元素中的數字,當數字到達零之后,就會將頁面跳轉到指定的鏈接,原理大致如此,這里就不多介紹了,具體可以參閱代碼注釋。
二.代碼注釋:
1.function redirect(){},聲明一個含糊,用于跳轉。
2.if(second<0) {location.href='http://wm.survivalescaperooms.com';} ,如果數字小于零,那么就會跳轉。
3.else{},否則進行倒計時效果。
4.if(navigator.appName.indexOf("Explorer")>-1),判斷是否是IE瀏覽器。
5.document.getElementById('totalSecond').innerText=second--,如果是IE瀏覽器則使用innerText屬性設置span元素中的數字值。
6.document.getElementById('totalSecond').textContent=second--,其他瀏覽器使用textContent屬性設置span元素中的數字值。
7.window.onload=function(){},當文檔完全加載完畢再去執行函數中的代碼。
8.if(navigator.appName.indexOf("Explorer")>-1){},如果是IE瀏覽器則使用innerText屬性獲取span元素中的內容。
9.second = document.getElementById('totalSecond').textContent,其他標準瀏覽器使用textContent屬性獲取span元素值。
10.setInterval("redirect()",1000),每隔一秒執行一次定時器函數。
三.相關閱讀:
1.indexof()函數可以參閱JavaScript中的lastIndexOf()方法使用詳解一章節。
2.setInterval()函數可以參閱setInterval()和setTimeout()的用法和區別示例介紹一章節。
以上內容是小編給大家分享的基于JavaScript實現定時跳轉到指定頁面的全部敘述,希望大家喜歡。
新聞熱點
疑難解答