JavaScript實現時間倒計時跳轉(推薦)_javascript技巧

來源:互聯網
上載者:User

1. setTimeout() 方法用於在指定的毫秒數後調用函數或計算運算式。

setTimeout() 只執行 code 一次。如果要多次調用,請使用 setInterval() 或者讓 code 自身再次調用 setTimeout()。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>setTimeout</title> </head> <body> <div id='div1'> </div> </body> </html> <script type="text/javascript"> //設定倒數秒數 var t = 10; //顯示倒數秒數 function showTime(){ t -= 1; document.getElementById('div1').innerHTML= t; if(t==0){ location.href='http://www.baidu.com'; } //每秒執行一次,showTime() setTimeout("showTime()",1000); } //執行showTime() showTime(); </script> 

2.setInterval() 方法可按照指定的周期(以毫秒計)來調用函數或計算運算式。

setInterval() 方法會不停地調用函數,直到 clearInterval() 被調用或視窗被關閉。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的參數。

<html><body><input type="text" id="clock" size="35" /><script language=javascript>var int=self.setInterval("clock()",50)function clock(){var t=new Date()document.getElementById("clock").value=t}</script></form><button onclick="int=window.clearInterval(int)">Stop interval</button></body></html>

下面給大家介紹下相關閱讀

 1.setInterval()函數可以參閱setInterval()函數用法詳解一章節。

2.location.href可以參閱Location對象的href屬性一章節。

3.innerHTML 屬性可以參閱js的innerHTML 屬性的用法一章節。

下面通過樣本(example)給大家介紹下 :

<html> <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="www.baidu.com"; //#設定跳轉的連結地址 } document.getElementById('show').innerHTML=""+t+"秒後跳轉"; // 顯示倒計時 t--; // 計數器遞減 } </script> <span id="show"></span> </body> </html> 

遇到的問題:

當將上述js 的方法 放在$(function(){......})中時, 瀏覽器會報 methodXX() is not defined;

應當將function(){}的定義放在 <script></script>中

以上所述是小編給大家介紹的JavaScript實現時間倒計時跳轉(推薦),希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對雲棲社區網站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.