js實現活動倒數計時

李文楊發表於2018-05-30
let startTime = 1527647143949; // 開始時間
    var time = new Countdown('timer',startTime);
    function Countdown (el,startTime) {
        this.startTime = startTime || '';
        this.el = el || '';
        // 輪詢計算時間
        this.loop = function () {
            var that = this;
            setInterval(function(){
                that.init();
            },1000);
        };
        // 格式化時分秒
        this.formatDuring = function (mss) {
            var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = parseInt((mss % (1000 * 60)) / 1000);
            return hours + ": " + (minutes < 10 ? '0'+minutes : minutes) + ": " + (seconds < 10 ? '0'+seconds : seconds);
        };
        // 初始化倒數計時
        this.init = function () {
            var endTime = this.startTime+(24*60*60*1000); // 結束時間 
            var timeLeft = endTime - new Date().getTime(); // 剩餘時間
            document.getElementById(this.el).innerHTML = this.formatDuring(timeLeft);
            this.loop();
        };
        this.init();
    };

 

相關文章