countdown.js 1.57 KB
/**
 * 倒计时控件
 * @author: wsl<shuiling.wang@yoho.cn>
 * @date: 2016/5/20
 */

let $ = require('yoho-jquery');

let $activityTime = $('.activity-time'),
    endTime = $activityTime ? $activityTime.data('time-s') : '';

let params = {
    anHour: 3600, // 1小时=?秒
    aMinute: 60, // 1分钟=?秒
    aSecond: 1, // 1秒=?秒
    timeDom: $activityTime, // 时间对象数组
    endTime: [endTime] // 时间差数组
};

// 倒计时
function getRTime(conf) {
    let showTime = '',
        d = 0,
        h = 0,
        m = 0,
        s = 0;

    conf.timeDom.each(function(key, item) {
        showTime = '';
        conf.endTime[key] = conf.endTime[key] - conf.aSecond;

        if (conf.endTime[key] > conf.aSecond) {
            d = Math.floor(conf.endTime[key] / conf.anHour / 24);
            h = Math.floor(conf.endTime[key] / conf.anHour % 24);
            m = Math.floor(conf.endTime[key] / conf.aMinute % 60);
            s = Math.floor(conf.endTime[key] / conf.aSecond % 60);

            showTime += d > 0 ? d + '天' : '';
            showTime += h > 0 ? h + '小时' : '';
            showTime += m + '分钟';
            showTime += s > 0 ? s + '秒' : '';

            if (showTime.length !== '') {
                showTime = '剩' + showTime;
            }

            $(item).find('span').html(showTime);
            $(item).fadeIn();
        } else {
            $(item).hide();
        }
    });
}

function startCountDown(p) {
    $.extend(params, p || {});
    setInterval(function() {
        getRTime(params);
    }, 1000);
}

module.exports = startCountDown;