jQuery倒计时插件,主要用来限时购买
1 /*
2 * 倒计时插件,主要用来限时购买
3 * By wayshan 版本1.0
4 * 使用方法:
5 * $(function(){
6 * $("#ElementId").countdown({
7 * Edate:"2012-12-21 15:14:23"
8 * });
9 * })
10
11 */
12 ;(function($){
13 $.fn.countdown = function(options){
14 if (this.length == 0){
15 return false;
16 }
17 return this.each(function(){
18 var Default = {
19 Sdate:null,//开始时间(格式为“2010-10-10 10:10:10”)可以设置为服务端的时间
20 Edate:null,//结束日期(格式为“2010-10-10 10:10:10”)
21 callback:function(){
22 return false;
23 }
24 },
25 _H_Text='小时',
26 _M_Text='分',
27 _S_Text='秒',
28 _lT = null,
29 _cT = new Date(),
30 _eT = null,
31 _elT = null,
32 ctime = null,
33 etime = null,
34 DomId = null,
35 _timeout = null,
36 _gt = function(){
37 if (_lT == null) {
38 _elT = (etime - ctime);
39 if (_elT < 0){
40 $('#'+DomId).html("<strong>0</strong>"+_H_Text+":<strong>0</strong>"+
41 _M_Text+":<strong>0</strong>"+_S_Text);
42 }
43 var _xT =Math.ceil(_elT/(24*60*60*1000));
44 _cT = parseInt(_cT.match(/\s(\d+)\D/)[1] * 3600)
45 + parseInt(_cT.split(":")[1] * 60)+ parseInt(_cT.split(":")[2]);
46 _eT = _xT * 24 * 3600 + parseInt(_eT.match(/\s(\d+)\D/)[1] * 3600)
47 + parseInt(_eT.split(":")[1] * 60) + parseInt(_eT.split(":")[2]);
48 _lT = _elT/1000;
49 }
50 if (_elT > 0) {
51 if (_lT >= 0) {
52 var _H = Math.floor(_lT / 3600);
53 var _M = Math.floor((_lT - _H * 3600) / 60);
54 var _S = (_lT - _H * 3600) % 60;
55 $('#'+DomId).html("<strong>" + _H + "</strong>"+_H_Text+":<strong>"
56 + _M + "</strong>"+_M_Text+":<strong>" + _S + "</strong>"+_S_Text);
57 _lT--;
58 } else {
59 clearInterval(_timeout);
60 if(s.callback && $.isFunction(s.callback)){
61 s.callback.call(this);
62 }
63 }
64 } else {
65 clearInterval(_timeout);
66 if(s.callback && $.isFunction(s.callback)){
67 s.callback.call(this);
68 }
69 }
70 },
71 strDateTime = function(str){
72 //判断日期时间的输入是否正确,类型必须形如为:2011-01-01 01:01:01
73 var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
74 var r = str.match(reg);
75 if(r==null)return false;
76 var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]);
77 return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]
78 &&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]);
79 }
80 var s = $.extend({}, Default, options || {});
81 DomId = this.id;
82 if (DomId == 'null'){
83 return;
84 }
85 _eT = s.Edate;
86 if (!strDateTime(_eT)){
87 alert('结束日期格式不正确');
88 return false;
89 }
90 if (s.Sdate != null){
91 _cT = s.Sdate;
92 }
93 _cT = _cT.toString();
94 cdate = _cT.replace(/-/g, '/');
95 _eT = _eT.toString();
96 edate = _eT.replace(/-/g, '/');
97 ctime = new Date(cdate);
98 etime = new Date(edate);
99 _timeout = setInterval(_gt, 1000)
100 });
101 }
102 })(jQuery);