endTime : number 结束的时间
showEndTime:true / false 是否显示结束的时间
endDom: dom 显示结束时间的html元素
ShowDistanceEndTime:true / false 是否显示距离结束时间的时分秒倒计时
showTime:{
showHour:dom 需要显示距离结束时间的小时数的html元素
showMinute:dom 需要显示距离结束时间的分钟数的html元素
showSecond:dom 需要显示距离结束时间的秒数的html元素
} 显示距离结束时间的时分秒的元素,以对象的形式传入
代码如下
(function () {function CountDown(option, self) {// 结束时间this.endTime = Date.parse(option.endTime) ? Date.parse(option.endTime) / 1000 : false;// 是否显示结束时间this.showEndTime = option.showEndTime || false;// 显示结束时间的html元素this.endDom = option.endDom || null;// 是否显示距离结束的时间this.ShowDistanceEndTime = option.ShowDistanceEndTime || true;/*** 显示距离时间的结束的html元素* showTime = {* showHour: $('.timmer__unit_hour'), 显示时的元素* showMinute: $('.timmer__unit_minute'), 显示分的元素* showSecond: $('.timmer__unit_second'), 显示秒的元素* }*/this.showTime = option.showTime;this.warp = self;this.timer = null;this.isEnd = false;}CountDown.prototype.init = function () {this.timeDifferens()// 判断是否显示结束时间if(this.showEndTime){var endtime = new Date(this.endTime * 1000);var hours = endtime.getHours() <= 0 ? "24": endtime.getHours();var minutes = endtime.getMinutes() <= 0 ? "00" :endtime.getMinutes()this.endDom.text(hours+":"+minutes)}},/*** 获取距离结束的时间的时间差*/CountDown.prototype.timeDifferens = function () {// 判断结束时间是否有误if (!this.endTime) { return false; }// 判断是否结束var nowTime = new Date().getTime() / 1000;if (nowTime > this.endTime) {this.isEnd = true;this.rendInfo()return;}var difference = this.endTime - nowTime;var self = this;this.timer = setInterval(() => {difference--;if (difference < 0) {self.isEnd = true;self.rendInfo()clearInterval(self.timer)}self.computeTime(difference)}, 1000);}/*** 换算时间差* @param {Number} time 时间差*/CountDown.prototype.computeTime = function (time) {this.hour = Math.floor(time / 3600);this.minute = Math.floor(time % 3600 / 60);this.second = Math.floor(time % 3600 % 60);this.rendInfo()}/*** 渲染信息*/CountDown.prototype.rendInfo = function () {if (this.ShowDistanceEndTime) {if (this.isEnd) {$(this.showTime.showHour).text('已');$(this.showTime.showMinute).text('结');$(this.showTime.showSecond).text('束');return;} else {if (this.hour < 10) {$(this.showTime.showHour).text("0" + this.hour);} else {$(this.showTime.showHour).text(this.hour);}if (this.minute < 10) {$(this.showTime.showMinute).text("0" + this.minute);} else {$(this.showTime.showMinute).text(this.minute);}if (this.second < 10) {$(this.showTime.showSecond).text("0" + this.second);} else {$(this.showTime.showSecond).text(this.second);}}}}$.fn.extend({countDown: function (option) {var obj = new CountDown(option, this);obj.init()}})})($ || jQuery)
调用方式演示
$('countdown-warp').countDown({endTime: '2020-8-30 24:00:00',showEndTime: true,endDom: $('.endTime'),ShowDistanceEndTime: true,showTime: {showHour: $('.timmer__unit_hour'),showMinute: $('.timmer__unit_minute'),showSecond: $('.timmer__unit_second'),},})
