JS倒计时特效

因为公司的业务是做教育的,所以页面上有关于考试时间的倒计时特效,这些考试时间都是定死的,每月都有几场,每次需要人工手动去修改,太麻烦,所以需求来了:


小二儿,上代码~

// 基于 jQuery

// 声明“类”,传入2个值:时间数组和Dom对象
function CountDown(times, elements) {
    this.times = times;
    this.eleDay = elements.eleDay;
    this.eleHour = elements.eleHour;
    this.eleMin = elements.eleMin;
    this.eleSec = elements.eleSec;
}

CountDown.prototype = {
    // 将数组中的格式时间转换为时间戳,返回新的数组
    timeStamp: function(arr) {
        var newArr = [];
        for (var i = 0; i < arr.length; i++) {
            var time = Date.parse(new Date(arr[i]));
            newArr[i] = time / 1e3;
        }
        return newArr;
    },

    // 获取当前时间,返回时间戳
    nowTime: function() {
        var nowTime = Date.parse(new Date());
        return nowTime = nowTime / 1e3;
    },

    // 计算时间差,返回差值时间戳
    timeDiff: function() {
        var timeDiff,
            newDate = new Date(),
            newArr = this.timeStamp(this.times);
        for (var i = 0; i < newArr.length; i++) {
            if (newArr[i] > this.nowTime()) {
                timeDiff = newArr[i] - this.nowTime();
                return timeDiff;
            }
        }
    },

    // 将差值时间戳格式化,替换元素文本,开始倒计时
    format: function() {
        var that = this,
            timeDiff = this.timeDiff(),
            timeFormat = setInterval(function() {
            if (timeDiff > 0) {
                timeDiff -= 1;
                var dayTxt = Math.floor((timeDiff / 3600) / 24),
                    hourTxt = Math.floor((timeDiff / 3600) % 24),
                    minTxt = Math.floor((timeDiff / 60) % 60),
                    secTxt = Math.floor(timeDiff % 60);
                that.eleDay && $(that.eleDay).text(dayTxt < 10 ? "0" + dayTxt : dayTxt);//计算天
                $(that.eleHour).text(hourTxt < 10 ? "0" + hourTxt : hourTxt);//计算小时
                $(that.eleMin).text(minTxt < 10 ? "0" + minTxt : minTxt);//计算分
                $(that.eleSec).text(secTxt < 10 ? "0" + secTxt : secTxt);// 计算秒
            } else {
                clearInterval(timeFormat);
            }
        }, 1e3);
    },

    init: function() {
        return this.format();
    }

};

var timeArr = ["2015/12/12 00:00:00", "2015/12/13 00:00:00", "2015/12/19 00:00:00"],
    elements = {
        eleDay: ".demo .day",
        eleHour: ".demo .hour",
        eleMin: ".demo .minute",
        eleSec: ".demo .second"
    };
var countDowns = new CountDown(timeArr, elements);

countDowns.init();
<div class="demo">
    <span class="day"></span>天
    <span class="hour"></span>小时
    <span class="minute"></span>分钟
    <span class="second"></span>秒
</div>
发表评论
* 昵称
* Email
* 网址
* 评论