dorseysen / One-Date-One-Question

this is a space for self-improvement of mine
1 stars 0 forks source link

2019-10-01:10月1号是国庆节,今天来写一个倒计时,期盼我们国庆节的到来。难度 ※ #147

Open dorseysen opened 5 years ago

dorseysen commented 5 years ago

// 2019-10-01:10月1号是国庆节,今天来写一个倒计时,期盼我们国庆节的到来
// 难度 ※ 

const nationalDayCountDown = {

    conf () {
        return {
            '国庆节': '10-01',
            '元旦': '01-01'
        }
    },
    timeContainer: {},

    init (festival, dom) {

        let _self = this;

        _self.config = _self.conf();

        let day = _self.config[festival];

        this.timeContainer[festival] = setInterval(function () {

            let option = Object.assign({}, {fes: festival}, _self.dataHandle(Number(day.split('-')[0]) - 1, day.split('-')[1]));

            dom.innerHTML = _self.tmpl(option);

        }, 1000);
    },

    dataHandle (month, date) {

        let dateTime = new Date(),
            year = dateTime.getFullYear(),
            festival = new Date(year, month, date),
            diff = festival.getTime() - dateTime.getTime();

        if(diff < 0){

            diff += this.isLeapYear( festival.getMonth() > 2 ? year : (year + 1) ) ? 366 * 24 * 60 * 60 * 1000 : 365 * 24 * 60 * 60 * 1000
        }

        return {

            date: Math.floor( diff / (24 * 60 * 60 * 1000) ),
            hour: Math.floor( (diff % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000) ),
            minute: Math.floor( (diff % (60 * 60 * 1000)) / (60 * 1000) ),
            second: Math.floor( (diff % (60 * 1000)) / 1000 )
        }
    },

    isLeapYear (year) {

        return (year % 400 === 0) || (year % 4 === 0 && year % 100 !== 0);
    },

    tmpl (option) {

        return `<p>${option.fes}倒计时: ${option.date} 天 ${option.hour} 时 ${option.minute} 分 ${option.second} 秒</p>`
    },
    stop (target) {

        clearInterval(this.timeContainer[target]);
    }

}

window.nationalDayCountDown = nationalDayCountDown;

nationalDayCountDown.init('国庆节', document.querySelector('.container'));
nationalDayCountDown.init('元旦', document.querySelector('.container1'));

// nationalDayCountDown.stop('元旦');

return "2019-10-01";