Rumah >hujung hadapan web >tutorial js >JS实现获取时间和设置倒计时代码分享
本文主要和大家分享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>
相关推荐:
Atas ialah kandungan terperinci JS实现获取时间和设置倒计时代码分享. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!