採用原生的js編寫一個倒計時器

<div id="clockdiv"> Days:<span class="days"></span><br> Hours:<span class="hours"></span><br> Minutes:<span class="minutes"></span><br> Seconds:<span class="seconds"></span> </div> <script type="text/javascript"> //跨頁面保存時鐘 if(document.cookie && document.cookie.match('myClock')){ var deadline = document.cookie.match(/(^|;)myClock=([^;]+)/)[2]; }else{ var timeInMinutes = 1; var currentTime = Date.parse(new Date()); var deadline = new Date(currentTime+timeInMinutes*60*1000); document.cookie = 'myClock = ' +deadline+ ';path=/;domain=.yourdomain.com'; } var totalTime; // var timeInMinutes = 10; // var currentTime = Date.parse(new Date()); // var deadline = new Date(currentTime+timeInMinutes*60*1000); // var deadline = "2016-8-3";//3/8/2016 定義有效的結束日期,日期的格式只要是Javascript Date.parse()方法可以解析的任何一種格式javascript

// initializeClock('clockdiv',deadline);//方法1,在首次顯示時鐘時有延遲 updateClock(); var timeinterval = setInterval("updateClock()",1000);//方法2,在首次顯示時鐘時有無延遲 //計算剩餘時間 function getTimeRemaining(endtime){ var t=Date.parse(endtime)-Date.parse(new Date()); var seconds = Math.floor((t/1000)%60); var minutes = Math.floor((t/1000/60)%60); var hours = Math.floor((t/(10006060))%24); var days = Math.floor(t/(10006060*24)); return{ 'total':t, 'das':days, 'hours':hours, 'minutes':minutes, 'seconds':seconds }; } //每過一秒刷新時間 function initializeClock(id,endtime){ var clock = document.getElementById(id); var timeinterval = setInterval(function(){ var t = getTimeRemaining(endtime); clock.innerHTML = 'days:' + t.days + '<br>' + 'hours:' + t.hours + '<br>' + 'minutes:' + t.minutes + '<br>' + 'seconds:' + t.seconds; if(t.total == 0){ clearInterval(timeinterval); } },1000); } function updateClock(){ var clock = document.getElementById('clockdiv'); var daysSpan = clock.querySelector('.days'); var hoursSpan = clock.querySelector('.hours'); var minutesSpan = clock.querySelector('.minutes'); var secondsSpan = clock.querySelector('.seconds'); var t = getTimeRemaining(deadline); daysSpan.innerHTML = t.days; hoursSpan.innerHTML = t.hours; minutesSpan.innerHTML = ('0'+ t.minutes).slice(-2); // secondsSpan.innerHTML = t.seconds; secondsSpan.innerHTML = ('0'+ t.seconds).slice(-2);//爲秒鐘前面加0 totalTime=t.total; // alert("222222222222"); if(totalTime==0){ window.clearInterval(timeinterval); } console.log(totalTime); } </script>java

相關文章
相關標籤/搜索