/** * 倒计时 * 前提条件:在对象上需要自定义属性 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); }