最近写的商品页面需要倒计时功能(day:hour:min:sec),直接上代码:
- 页面效果
- index.html
<div class="se-kl"> <div class="se-info">EXPRIES IN:</div> <div class="se-count"> <div class="se-day"><span class="se-txt">00</span></div> <span class="sm sm_01">:</span> <div class="se-hour"><span class="se-txt">00</span></div> <span class="sm sm_02">:</span> <div class="se-min"><span class="se-txt">00</span></div> <span class="sm sm_03">:</span> <div class="se-sec"><span class="se-txt">00</span></div> </div> </div>
- css代码
.se-kl { width: 218px; height: 110px; margin: 20px auto 20px auto; position: relative; display: flex; justify-content: center;} .se-info { position: absolute; top: 15px; text-align: center; width: 100%; font-size: 16px; color: #fff; font-weight: 1000; } .se-count { position: absolute; top: 40px; left: 22px; height: 40px; font-size: 20px;} .se-day{ position:relative;} .sm{ font-size: 16px;color: #fff; } .sm_01{ position:absolute;top: 20%;left: 22%; } .sm_02{ position:absolute;top: 20%;left: 47%;} .sm_03{ position:absolute;top: 20%;left: 72%;} .se-day,
.se-hour,
.se-min,
.se-sec { position: relative; width: 40px; height: 40px; float: left; text-align: center; line-height: 40px; margin-right: 5px; } .se-txt { font-size: 24px; font-weight: bold; color: #fff; }
注:因为在商品页面写的,所以用了比较多的定位,可忽略。
- js代码
var spans=document.getElementsByClassName("se-txt"); var endTime=new Date('2020/10/2 16:43:00');//未来时间 var timer=null; clearInterval(timer); timer =setInterval(countTime,1000); function countTime(){ var nowTime=new Date();//现在时间 var lastTime=parseInt((endTime-nowTime)/1000);//剩余时间=未来时间-现在时间(未来时间距离现在的秒数) if(lastTime>=0){ var day=parseInt(lastTime/60/60/24);//换算成天数,一天有86400秒 var hour=parseInt(lastTime/60/60%24);//余数代表剩下的小时 var min=parseInt(lastTime/60%60);//代表分钟 var sec=parseInt(lastTime%60);//代表秒数 //给不足10的数前面添加一个0 if(day <10){ day="0"+day; } if(hour <10){ hour ="0"+hour; } if(min <10){ min ="0"+min; } if(sec <10){ sec="0" + sec; } // console.log(day); // console.log(hour); spans[0].innerHTML=day;//向对象“se-txt”插入内容 spans[1].innerHTML=hour; spans[2].innerHTML=min; spans[3].innerHTML=sec; }else{ clearInterval(timer);//清除时间 } }