标签:style class blog code http tar
倒计时网上一大堆,所以也没有什么好说的,支持:1.年,月,日,天,时分秒等倒计时。
JS代码如下:
/* * js简单的倒计时 * @param {date,obj} 日期 对象格式 */ function CountDown(date,obj) { var self = this; self.date = date; self.obj = obj; self._init(); }; $.extend(CountDown.prototype,{ _init: function(){ var self = this, obj = self.obj; var dateTime = self._calculateTime(); if(obj.sec) { $(obj.sec).html(dateTime.sec); } if(obj.mini) { $(obj.mini).html(dateTime.mini); } if(obj.hour) { $(obj.hour).html(dateTime.hour); } if(obj.day) { $(obj.day).html(dateTime.day); } if(obj.month) { $(obj.month).html(dateTime.month); } if(obj.year) { $(obj.year).html(dateTime.year); } // setInterval 会有误差 大概每小时有5秒的误差 故用setTimeout做计时器 精准更高 t && clearTimeout(t); var t = setTimeout(function(){ self._init(); }, 1000); }, _zero: function(n){ var n = parseInt(n,10); if(n > 0) { if(n < 10) { n = "0" + n; } return String(n); }else { return n = "00"; } }, _calculateTime: function(){ var self = this, date = self.date || Date.UTC(2050, 0, 1); var end = new Date(date), now = new Date(); // getTimezoneOffset() 方法可返回格林威治时间和本地时间之间的时差,以分钟为单位。 var leftTime = Math.round((end.getTime() - now.getTime())/1000) + end.getTimezoneOffset() * 60; var obj = { sec: "00", mini: "00", hour: "00", day: "00", month: "00", year: "0" }; if(leftTime > 0) { obj.sec = self._zero(leftTime % 60); obj.mini = Math.floor(leftTime / 60) > 0 ? self._zero(Math.floor(leftTime / 60) % 60) : "00"; obj.hour = Math.floor(leftTime / 3600) > 0 ? self._zero(Math.floor(leftTime/3600) % 24) : "00"; obj.day = Math.floor(leftTime / (24 * 3600)) > 0 ? self._zero(Math.floor(leftTime / (24*3600)) % 30) : "00"; obj.month = Math.floor(leftTime / (30 * 24 * 3600)) > 0 ? self._zero(Math.floor(leftTime / (30 * 24 * 3600)) % 12) : "00"; //年份,按按回归年360天秒算 obj.year = Math.floor(leftTime / (360 * 30 * 24 * 3600)) > 0 ? Math.floor(leftTime / (360 * 30 * 24 * 3600)) : "0"; } return obj; } });
假如HTML如下:
<span class="hour"></span>时 <span class="mini"></span>分 <span class="sec"></span>秒
那么我们可以这样初始化代码:
var d = 1419509471000; //var d = Date.UTC(2030, 6, 27, 16, 34); var obj = { sec: $(".sec"), mini: $(".mini"), hour: $(".hour") } new CountDown(d, obj);
标签:style class blog code http tar
原文地址:http://www.cnblogs.com/tugenhua0707/p/3809184.html