本文主要和大家分享JS實作取得時間和設定倒數計時器,希望能幫助大家。
只做筆記記錄一下,主要用到Date
和setInterval
第一個倒數計時的設定:
<script type="text/javascript"> var timeBox = document.querySelector("#time"); function countdown(){ var nowTime = new Date(); var targetTime = new Date("2018/2/27 15:44:15"); var spanTime = targetTime-nowTime; if(spanTime <=0){ timeBox.innerHTML="立即抢购"; clearInterval(countdown); }else{ var hours = Math.floor(spanTime/(1000*60*60)); spanTime-=hours*60*60*1000; var minute = Math.floor(spanTime/(1000*60)); spanTime-=minute*60*1000; var second = Math.floor(spanTime/1000); hours<10 ? hours='0'+hours : hours; minute<10 ? minute='0'+minute : minute; second<10 ? second='0'+second : second; timeBox.innerHTML=hours+':'+minute+':'+second; } } var timer = window.setInterval(countdown,1000); </script>
第二個,顯示目前日期:
<script type="text/javascript"> var timeBox = document.querySelector("#time"); function countdown(){ var date = new Date(); var hours = date.getHours(); var minute = date.getMinutes(); var second = date.getSeconds(); hours =checkTime(hours); minute =checkTime(minute); second =checkTime(second); timeBox.innerHTML = hours+':'+minute+':'+second; } // 检测时间数字是否小于10,在小于10的数字前加一个‘0’ function checkTime(i){ i<10 ? i="0"+i :i; return i; } var timer = window.setInterval(countdown,1000); </script>
相關推薦:
以上是JS實現獲取時間和設定倒數計時器分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!