js 倒计时

 

/**
 * 倒计时
 * 前提条件:在对象上需要自定义属性 data-now/data-end
 * 分别表示当前时间秒数以及结束时间秒数
 * 
 * demo1: 
 *  $('.countdown').each(function () {
 *      var my = $(this);
 *      countDown(my);
 *  });
 *
 * demo2: 
 *  $('.countdown').each(function () {
 *      var my = $(this);
 *      countDown(my, function () {
 *          console.log(1);
 *      });
 *  });
 */

function countDown (obj, func) {
    var nowTime = obj.data('now'),
        endTime = obj.data('end'),
        timerFn;

    var nD, nH, nM, nS, outStr, times;

    function dodo() {
        times = (endTime - nowTime) * 1000;            //时间差

        if (times > 0) {
            nD = Math.floor(times / (1000 * 60 * 60 * 24));
            nH = Math.floor(times / (1000 * 60 * 60)) % 24;
            nM = Math.floor(times / (1000 * 60)) % 60;
            nS = Math.floor(times / 1000) % 60;
            if (func) {
                outStr = func(nD, nH, nM, nS);
            } else {
                outStr = '<span class="icon_time"></span><span class="brand-days"><em>' + nD 
                        + '</em><i></i></span>' 
                        + '<span class="brand-hours"><em>' + nH + '</em><i></i></span>'
                        + '<span class="brand-minutes"><em>' +nM + '</em><i></i></span>'
                        + '<span class="brand-seconds"><em>' + nS + '</em><i></i></span>';
            }
        } else {
            clearInterval(timerFn);
        }
        obj.html(outStr);
        nowTime++;
    }

    dodo();
    timerFn = setInterval(dodo, 1000);
}

 

 

posted @ 2015-06-08 14:36  白小虫  阅读(199)  评论(0编辑  收藏  举报