本文實例為大家分享了js實現網頁同時進行多個倒計時的具體代碼,供大家參考,具體內容如下
創建一個時間類Timer.
每個商品的倒計時生成一個實例:var time = new Timer();
/***startime 應該是毫秒數*/ var Alarm = function (startime, endtime, countFunc, endFunc) { this.time = Math.floor((endtime - startime) / 1000); //時間 this.countFunc = countFunc; //計時函數 this.endFunc = endFunc; //結束函數 this.flag = 't' + Date.parse(new Date()); // };Alarm.prototype.start = function () { var self = this; self.flag = setInterval(function () { if (self.time < 0) { clearInterval(self.flag); self.endFunc(); console.log('計時結束'); } else { var minute, hour, day, second; day = Math.floor(self.time / 60 / 60 / 24) < 10 ? '0' + Math.floor(self.time / 60 / 60 / 24) : Math.floor(self.time / 60 / 60 / 24); hour = Math.floor(self.time / 60 / 60 % 24) < 10 ? '0' + Math.floor(self.time / 60 / 60 % 24) : Math.floor(self.time / 60 / 60 % 24); minute = Math.floor(self.time / 60 % 60) < 10 ? '0' + Math.floor(self.time / 60 % 60) : Math.floor(self.time / 60 % 60); second = Math.floor(self.time % 60) < 10 ? '0' + Math.floor(self.time % 60) : Math.floor(self.time % 60); //倒計時執行函數 self.countFunc(second, minute, hour, day); self.time--; } }, 1000);}
如果調用:
var time1 = new Alarm(startime, endtime, countFunc, endFunc);time1.start(); var time2 = new Alarm(startime, endtime, countFunc, endFunc);time2.start();...
調用示例:
var countTime = function () { var eles = $('.count_time'), len = eles.length; for (; len > 0; len--) { var ele = eles.eq(len - 1); (function (ele) { startTime = new Date(ele.attr('data-start-time')).getTime(), endTime = new Date(ele.attr('data-end-time')).getTime(), alarm = new Alarm(startTime, endTime, function (second, minute, hour, day) { //計時鐘 ele.text(hour + ':' + minute + ':' + second); }, function () { //倒計時結束 ele.text('00:00:00'); window.location.reload(); }); alarm.start(); })(ele); }};countTime();
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答