function newTimeRun(nowTime, beginTime, overTime,classname){ var unStartTimeLength = new Date(beginTime) - new Date(nowTime),//未开始的时间长度 //var unStartTimeLength = new Date(beginTime).getTime() - new Date(nowTime).getTime(),//未开始的时间长度 endTimeLength = new Date(nowTime) - new Date(overTime),//已过期的时间长度 timingLength = new Date(overTime) - new Date(nowTime);//抢购中的时间长度 //未开始 if(unStartTimeLength > 0){ countDown(unStartTimeLength,function(time){ var hour = formatNum(time[0] * 24 + time[1]), min = formatNum(time[2]), sec = formatNum(time[3]); classname.html(‘<span class="timeTxt">离特惠开始还剩 <span class="remain">‘ + hour + ‘:‘ + min + ‘:‘ + sec +‘</span></span>‘) }, function(){ countDown(timingLength,function(time){ var hour = time[0] * 24 + time[1], min = time[2], sec = time[3]; classname.html(‘<span class="timeTxt">离特惠结束还剩 <span class="remain">‘ + hour + ‘:‘ + min + ‘:‘ + sec +‘</span></span>‘); },function(){ classname.html(‘<span class="timeTxt">本场特惠已结束</span>‘); }) }); } //过期 else if(endTimeLength >=0){ classname.html(‘<span class="timeTxt">本场特惠已结束</span>‘); } //开始-结束 else{ countDown(timingLength,function(time){ var hour = formatNum(time[0] * 24 + time[1]), min = formatNum(time[2]), sec = formatNum(time[3]); classname.html(‘<span class="timeTxt">离特惠结束还剩 <span class="remain">‘ + hour + ‘:‘ + min + ‘:‘ + sec +‘</span></span>‘); },function(){ classname.html(‘<span class="timeTxt">本场特惠已结束</span>‘); }) }}
function countDown(times, fn, endFn) { if (typeof times === "number") { times = calculateTime(times); } else if (Object.prototype.toString.apply(times) === "[object Date]") { var ms = times.getTime() - new Date().getTime() times = calculateTime(ms); setTimeout(function () { countDown(times, fn, endFn); }, ms % 1000); return; } fn(times); // 一开始先执行一次 var intervalMac = setInterval(function () { var timesLen = times.length, scales = [24, 60, 60], scalesLen = scales.length; for (var i = timesLen; i--;) { if (times[i] > 0) { times[i] = times[i] - 1; break; } // 等于0,非首位的处理 if (i !== 0) { times[i] = scales[scalesLen -(timesLen - i)] - 1; } else { // 一直到首位都为0,倒计时结束 for (var j = 0; j < times.length; j++) { times[j] = 0; } clearInterval(intervalMac); return; } } fn(times); if(typeof endFn === "function"){ var isEnd = true; for(var i = 0,len = times.length;i < len;i++){ if(times[i] !== 0){ isEnd = false; break; } } if(isEnd){ endFn(times); } } }, 1000);}//把毫秒转换成数组[day, hour, minute, second]function calculateTime(time) { if (time < 0) { return [0, 0, 0, 0]; } time = Math.floor(time / 1000); var times = [], scales = [86400, 3600, 60]; for (var i = 0; i < scales.length; i++) { times.push(Math.floor(time / scales[i])); time %= scales[i]; } times.push(time); return times;} 调用
$(".box3").each(function(i,elem){ var date = new Date(); var uStartTime = $(elem).attr("zy-s-time"), uEndTime = $(elem).attr("zy-e-time"), timeSpan = $(".timeW",elem); newTimeRun(date,uStartTime,uEndTime,timeSpan);}) 注意时间格式
时间: 2024-11-08 15:40:19