倒计时

发布于 2020-11-11  65 次阅读


    var box=document.getElementById('list-box');
    var list=box.querySelectorAll('li');
    var listTime=box.querySelectorAll('.time');
    var btn=box.querySelectorAll('.limited-box');
    for(var i=0;i<list.length;i++){
        var starttime=listTime[i].getAttribute('data-starttime');
        var endtime=listTime[i].getAttribute('data-endtime');
        toTime(listTime[i],starttime,endtime,btn[i]);
    }
    //时间戳转日期
    function  setTime(time){
        var date = new Date(time);
        Y = date.getFullYear() + '-';
        M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        D = date.getDate() + ' ';
        h = date.getHours() + ':';
        m = date.getMinutes() + ':';
        s = date.getSeconds();
        return (Y+M+D+h+m+s)
    }
    function addNum(num){
        if(num<10){
            return '0'+num;
        }
        else{
            return num;
        }
    };
    //倒计时开始
    function toTime(obj,wDays,nDays,btn){
        var time=null;
        var wDays = new Date(wDays);
        var nDays = new Date(nDays);
        time=setInterval(function(){
            var nowDate = new Date();
            var disTime = wDays.getTime() - nowDate.getTime();
            if(disTime <= 0){
                var disTimes = nDays.getTime() - nowDate.getTime();
                if(disTimes<=0){
                    clearInterval(time);
                    obj.innerHTML ='已结束';
                }else {
                    var token=Times(nDays,nowDate);
                    obj.innerHTML ='距结束:'+token.iDays+'天'+token.iHours+'时'+token.iMins+'分'+token.iSec+'秒';
                    btn.classList.remove('blue');
                    btn.classList.add('red');
                }
            }else {
                var token=Times(wDays,nowDate);
                obj.innerHTML ='距开始:'+token.iDays+'天'+token.iHours+'时'+token.iMins+'分'+token.iSec+'秒';
                btn.classList.remove('red');
                btn.classList.add('blue');
            }
        },100);
    };
    function Times(wDays,nowDate) {
        var cha = Math.ceil((wDays.getTime()-nowDate.getTime())/1000);
        var iDays = Math.floor(cha/3600/24);
        var iHours = addNum( Math.floor(cha/3600%24) );
        var iMins = addNum( Math.floor(cha/60%60) );
        var iSec = addNum( Math.ceil(cha%60) );
        return {
            iDays:iDays,
            iHours:iHours,
            iMins:iMins,
            iSec:iSec
        };
    }

一沙一世界,一花一天堂。君掌盛无边,刹那成永恒。