本章節介紹一段代碼實例,此代碼能夠判斷當前日期是否已經倒計時結束,此代碼中并沒有倒計時效果,只是判斷是否倒計時完成,比如購物網站優惠期限等,雖然實際應用中,很少會出現類似的代碼,不過希望能夠給瀏覽者帶來一定的啟示作用。
代碼如下:
function done(){ var str=$('#end').text(); var out=str.match(/d+/g); console.log(out); var h=parseInt(out[0]),m=parseInt(out[1]),s=parseInt(out[2]); console.log(h+'#'+m+'#'+s); var calc=h*3600+m*60+s; console.log(calc); if(calc==0){ //code } else{ console.log('等待..'); } var t=setTimeout('done()',1000); } done();
上面只是代碼片段,不能夠演示,下面介紹一下它的實現過程。
一.代碼注釋:
1.function done(){},此函數實現判斷倒計時結束效果。
2.var str=$('#end').text(),獲取指定元素中的文本內容,本代碼中應該倒計時當前時間.
3.var out=str.match(/d+/g),獲取時間日期中數字的數組。
4.var h=parseInt(out[0]),m=parseInt(out[1]),s=parseInt(out[2]),分別獲取小時、分鐘和秒。
5.var calc=h*3600+m*60+s,轉換成秒。
6.if(calc==0){//code},判斷倒計時是否結束,然后指定相應的操作。
7.var t=setTimeout('done()',1000),每隔一秒執行一次判斷函數。
8.done(),執行此函數。
jquery實現倒計時代碼如下所示:
$(function(){ var tYear = ""; //輸入的年份 var tMonth = ""; //輸入的月份 var tDate = ""; //輸入的日期 var iRemain = ""; //開始和結束之間相差的毫秒數 var sDate = ""; //倒計的天數 var sHour = ""; //倒計時的小時 var sMin = ""; //倒計時的分鐘 var sSec = ""; //倒計時的秒數 var sMsec = ""; //毫秒數 //通用工具函數,在個位數上加零,根據傳的N的參數,來設前面加幾個零 function setDig(num,n){ var str = ""+num; while(str.length<n){ str="0"+str } return str; } //獲得相差的天,小時,分鐘,秒 function getdate(){ //創建開始時間和結束時間的日期對象 var oStartDate = new Date(); var oEndDate = new Date(); //獲取文本框的值 tYear = $("#tyear").val(); tMonth = $("#tmonth").val(); tDate = $("#tdate").val(); //設置結束時間 oEndDate.setFullYear(parseInt(tYear)); oEndDate.setMonth(parseInt(tMonth)-1); oEndDate.setDate(parseInt(tDate)); oEndDate.setHours(0); oEndDate.setMinutes(0); oEndDate.setSeconds(0); //求出開始和結束時間的秒數(除以1000) iRemain = (oEndDate.getTime() - oStartDate.getTime())/1000; //總的秒數除以一天的秒數,再取出整數部分,就得出有多少天。 sDate = setDig(parseInt(iRemain/(60*60*24)),3); //總的秒數除以一天的秒數,然后取其中的余數,就是把整數天扣除之后,剩下的總秒數。 iRemain %= 60*60*24; //剩下的總秒數除以一個小時的秒數,再取整數部分,就是有多少小時。 sHour = setDig(parseInt(iRemain/(60*60)),2) //剩下的總秒數除以一個小時的秒數,再取其余數,這個余數,就是扣除小時這后,剩下的總秒數。 iRemain %= 60*60; //剩下的總秒數除以一分鐘的秒數,再取其整數部分,就是有多少分鐘。 sMin = setDig(parseInt(iRemain/60),2) //剩下的總秒數除以一分鐘的秒數,再取其余數,這個余數,就是扣除分鐘之后,剩下的總秒數。 iRemain%=60; //剩下的秒數 sSec = setDig(iRemain,2); //毫秒數 sMsec = sSec*100; } //更改顯示的時間 function updateShow(){ $(".showdate span").text(tYear+"-"+tMonth+"-"+tDate); $(".count span").each(function(index, element) { if(index==0){ $(this).text(sDate); }else if(index==1){ $(this).text(sHour); }else if(index == 2){ $(this).text(sMin); }else if(index == 3){ $(this).text(sSec); }else if(index == 4){ $(this).text(sMsec); } }); } //每一秒執行一次時間更新 function autoTime(){ getdate(); //如果小于零,清除調用自己,并且返回 if(iRemain<0){ clearTimeout(setT); return; } updateShow(); var setT = setTimeout(autoTime,1000); } //點擊按鈕開始計時 $("button").click(function(){ autoTime(); }) })
記錄需要注意的地方:
1.取模運算:
iRemain %= 60*60*24;
就是返回余數,在這個實例中的余數,就是把整數拿走后,剩下的秒數。
2.工具函數 setDig(num,n)
可以根據傳入的參數,自動在傳入的數字前加零