Js 之时间倒计时
一、效果图
二、代码
<h1>Countdown Clock</h1> <div id="clockdiv"> <div> <span class="days">00</span> <div class="smalltext">Days</div> </div> <div> <span class="hours">00</span> <div class="smalltext">Hours</div> </div> <div> <span class="minutes">00</span> <div class="smalltext">Minutes</div> </div> <div> <span class="seconds">00</span> <div class="smalltext">Seconds</div> </div> </div> <script type="text/javascript"> let ut = {}; const countDown = function(time, fn) { let maxtime = time - new Date().getTime(), //剩余秒 timer = setInterval(function() { if (maxtime >= 0) { const dd = parseInt(maxtime / 60 / 60 / 24, 10), //计算剩余的天数 hh = (Array(2).join(0) + parseInt(maxtime / 60 / 60 % 24, 10)).slice(-2), //计算剩余的小时数 mm = (Array(2).join(0) + parseInt(maxtime / 60 % 60, 10)).slice(-2), //计算剩余的分钟数 ss = (Array(2).join(0) + parseInt(maxtime % 60, 10)).slice(-2); //计算剩余的秒数 fn({dd, hh, mm, ss}); --maxtime; } else { clearInterval(timer) fn({}) } }, 1000) }, showtime = function(time) { const clock = document.getElementById("clockdiv"), daysSpan = clock.querySelector('.days'), hoursSpan = clock.querySelector('.hours'), minutesSpan = clock.querySelector('.minutes'), secondsSpan = clock.querySelector('.seconds'); if(undefined === time.ss) { clock.innerHTML = '结束了'; return false; } if(undefined === ut.dd || time.dd !== ut.dd) daysSpan.innerHTML = time.dd; if(undefined === ut.hh || time.hh !== ut.hh) hoursSpan.innerHTML = time.hh; if(undefined === ut.mm || time.mm !== ut.mm) minutesSpan.innerHTML = time.mm; secondsSpan.innerHTML = time.ss; ut = time; }; countDown(new Date().getTime() + 60 * 60 * 24 * 10, showtime); </script>
<style type="text/css"> body{ text-align: center; background: #00ECB9; font-family: sans-serif; font-weight: 100; } h1{ color: #396; font-weight: 100; font-size: 40px; margin: 40px 0px 20px; } #clockdiv{ font-family: sans-serif; color: #fff; display: inline-block; font-weight: 100; text-align: center; font-size: 30px; } #clockdiv > div{ padding: 10px; border-radius: 3px; background: #00BF96; display: inline-block; } #clockdiv div > span{ padding: 15px; min-width: 48px; border-radius: 3px; background: #00816A; display: inline-block; } .smalltext{ padding-top: 5px; font-size: 16px; } </style>