一個網頁倒計時的實現

來源:互聯網
上載者:User

標籤:io   2014   re   問題   c   cti   

        最近要做一個網站上的活動倒計時的功能。在網上搜了一下,網上關於js倒計時的代碼倒是不少,但是正正可以應用到生產環境的則是少之又少。

         比如我用到的這個就是這樣的:

var endDate=new Date(2014,7,25,23,59,59);var begin = new Date();var intDiff=Math.round((endDate.getTime()-begin)/1000);//初始日期function timer(intDiff){window.setInterval(function(){var day=0,hour=0,minute=0,second=0;//時間預設值if(intDiff > 0){day = Math.floor(intDiff / (60 * 60 * 24));hour = Math.floor(intDiff / (60 * 60)) - (day * 24);minute = Math.floor(intDiff / 60) - (day * 24 * 60) - (hour * 60);second = Math.floor(intDiff) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);}if(day==0&&hour==0&&minute==0&&second<=0){$("#timeshow").html("活動結束。");}if (minute <= 9) minute = ‘0‘ + minute;if (second <= 9) second = ‘0‘ + second;$(‘#day_show‘).html(day+‘天‘);$(‘#hour_show‘).html(hour+‘小時‘);$(‘#minute_show‘).html(minute+‘分‘);$(‘#second_show‘).html(second+‘秒‘);intDiff--;}, 1000);} $(function(){timer(intDiff);});

看到了沒,由於js是運行在用戶端的,無法拿到伺服器的時間,所以會導致“一千個讀者眼裡又一千個哈姆雷特”,這樣是不對的,所以要獲得伺服器的時間。

第一想到的是用ajax請求獲得伺服器的時間,但是會有問題,ajax是非同步請求,js執行到那一段的時候ajax還沒有執行完成,所以會出現取不到值得情況。所以否決了這樣的做法。

解決方案是:

  <input type="hidden" id="serverTime" value="<%= request.getAttribute("time")%>"/>

在請求到這個頁面之前,把時間放到atrribute裡面,在頁面拿到這個值,放到一個隱藏欄位裡面。注意:定時器的代碼要放到取值操作的後米阿尼,否則會出現隱藏欄位時空的情況。


Get!


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.