我们利用学过的定时器来实现一下京东倒计时的案例:
效果如下:
JS区域实现:
<script>document.addEventListener('DOMContentLoaded',function(){ varhour=document.querySelector('.left'); varminute=document.querySelector('.center'); varsecond=document.querySelector('.right'); timer(); varclock=window.setInterval(function(){ timer(); },1000) functiontimer(){ varnowtime=+newDate(); varaimtime=+newDate("2022-3-8 19:30:00"); time=(aimtime-nowtime)/1000; varh=parseInt(time/60/60%24); h=h<10?'0'+h:h; hour.innerHTML=h; varm=parseInt(time/60%60); m=m<10?'0'+m:m; minute.innerHTML=m; vars=parseInt(time%60); s=s<10?'0'+s:s; second.innerHTML=s; } }) </script>
完整代码实现:
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Document</title><style>*{ margin: 0px; padding: 0px; } .box{ box-sizing: border-box; margin: 100pxauto; width: 500px; height: 600px; background-color: rgb(216, 0, 0); } .top{ box-sizing: border-box; width: 500px; height: 350px; padding: 5px; padding-top: 35px; text-align: center; line-height: 130px; font-size: 70px; color: rgb(255, 255, 255); font-weight: bold; } .bottom{ padding: 10px; } .left{ box-sizing: border-box; margin: 10px; float: left; width: 140px; height: 140px; background-color: rgb(0, 0, 0); color: azure; padding: 19px; font-size: 80px; font-weight: bold; } .center{ box-sizing: border-box; margin: 10px; float: left; width: 140px; height: 140px; background-color: rgb(0, 0, 0); color: azure; padding: 19px; font-size: 80px; font-weight: bold; } .right{ box-sizing: border-box; margin: 10px; float: left; width: 140px; height: 140px; background-color: rgb(0, 0, 0); color: azure; padding: 19px; font-size: 80px; font-weight: bold; } </style></head><body><script>document.addEventListener('DOMContentLoaded',function(){ varhour=document.querySelector('.left'); varminute=document.querySelector('.center'); varsecond=document.querySelector('.right'); timer(); varclock=window.setInterval(function(){ timer(); },1000) functiontimer(){ varnowtime=+newDate(); varaimtime=+newDate("2022-3-8 19:30:00"); time=(aimtime-nowtime)/1000; varh=parseInt(time/60/60%24); h=h<10?'0'+h:h; hour.innerHTML=h; varm=parseInt(time/60%60); m=m<10?'0'+m:m; minute.innerHTML=m; vars=parseInt(time%60); s=s<10?'0'+s:s; second.innerHTML=s; } }) </script><divclass="box"><divclass="top">11.11<br>秒杀倒计时</div><divclass="bottom"><divclass="left"></div><divclass="center"></div><divclass="right"></div></div> </div></body></html>