活动倒计时,可同步服务器时间,倒计时格式随意设置
使用说明
/* #活动倒计时,可同步服务器时间 startTime:起始时间 endTime:结束时间 format_str:字符模板 speed:倒计时执行速度 callback:倒计时结束回调 $('.xxx').countDown_str({ startTime:'2018-09-28 11:09:00', endTime: '2018-09-29 11:09:00', format_str: '{d}{h}{m}{s}{hs}' }); //字符模板详细说明 {d}天数 {h}小时 {m}分钟 {s}秒 {hs}毫秒 */
插件代码
$.fn.countDown_str = function (options) { var defaults = { startTime: '2018-09-28 11:09:00', endTime: '2018-09-29 11:09:00', speed: 1000, format_str: '{d}{h}{m}{s}{hs}', callback: function () { } } var opt = $.extend({}, defaults, options); return this.each(function () { var that = this, timer = ''; function init() { var nowTimeStamp = new Date().getTime();//服务器的开始时间 var nowTimeStamp_server = new Date(opt.startTime).getTime(); this.totalTime = nowTimeStamp - nowTimeStamp_server;//服务器与本地时间差 } init.prototype.format = function (str, args) { var result = str; if (arguments.length > 0) { if (arguments.length == 2 && typeof (args) == "object") { for (var key in args) { if (args[key] != undefined) { var reg = new RegExp("({" + key + "})", "g"); result = result.replace(reg, args[key]); } } } } return result; }; init.prototype.outputTime = function () { var date = this.date, endTime = opt.endTime, format_str = opt.format_str; var nowTimeStamp = new Date().getTime(); var endTimeStamp = new Date(endTime).getTime(); var surplusTime = endTimeStamp - nowTimeStamp + this.totalTime; var d = parseInt((surplusTime / (1000 * 60 * 60 * 24))); var _d = d < 10 ? '0' + d : d; var h = parseInt((surplusTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); //时 var _h = h < 10 ? '0' + h : h; var m = parseInt((surplusTime % (1000 * 60 * 60)) / (1000 * 60)); //分 var _m = m < 10 ? '0' + m : m; var s = ((surplusTime % (1000 * 60)) / 1000).toString(); //秒 var s1 = s.toString().split('.')[0]; //秒 var _s1 = s1 < 10 ? '0' + s1 : s1; var _s3 = (s - s1).toFixed(3).toString().substring(2); if (surplusTime > 0) { format_str = init.format(format_str, { d: _d, h: _h, m: _m, s: _s1, hs: _s3 }); } else { format_str = init.format(format_str, { d: '00', h: '00', m: '00', s: '00', hs: '000' }); clearInterval(timer); //定时器结束灰调 if (typeof opt.callback == 'function') { opt.callback(); } } $(that).html(format_str); } var init = new init(); init.outputTime(); timer = setInterval(function () { init.outputTime(); }, opt.speed); }); }