<!doctype html> <head> <meta http-equiv="content-type" content="text/html; charset=GBK"> <title> </title> </head> <body> <style> #CountdowTest01,#CountdowTest02{display:block;width:400px;} .countdown-over{color:red} .countdown-d,.countdown-h,.countdown-m,.countdown-s{font-weight:700;} </style> <span id="CountdowTest01"> </span> <span id="CountdowTest02"> </span> <script> /* * class Countdown倒计时效果 * @param {ELEMENT} 可传入元素、ID * @return {Countdown INSTANCE} * @author: Countdown */ function Countdown () { if (!(this instanceof Countdown)) { return new Countdown(); } this.init.apply(this, arguments); } Countdown.prototype={ constructor: Countdown, init:function (el,opts){ this.el=el; this.timer=null; this.time=opts.time || +new Date; this.showMS=Boolean(opts.showMS); this.overTip=opts.overTip || ' <span class="countdown-over">活动结束! </span>'; this.format=opts.format || function (d,h,m,s,ms){ var ret=[ ' <span class="countdown-d">'+d+' </span>天', ' <span class="countdown-h">'+h+' </span>小时', ' <span class="countdown-m">'+m+' </span>分', ' <span class="countdown-s">'+s+' </span>秒' ]; if (this.showMS) { ret.push(' <span class="countdown-ms">'+ms+' </span>'); } return ret.join(''); }; this.second2Date(); }, second2Date:function (){ var self=this, seconds=self.time-(+new Date), dd,hh, mm, ss; if (!seconds || seconds < 0){ clearTimeout(this.timer); this.el.innerHTML= this.overTip; return; } dd=Math.floor(seconds / 86400000); seconds -= dd * 86400000; hh = Math.floor(seconds / 3600000); seconds -= hh * 3600000; if (hh < 10) { hh = "0" + hh; } mm = Math.floor(seconds / 60000); seconds -= mm * 60000; if (mm < 10){ mm = "0" + mm; } ss = Math.floor(seconds / 1000); seconds -= ss * 1000; if (ss < 10){ ss = "0" + ss; } if (this.showMS) { ms= Math.floor(seconds / 10); if (ms < 10){ ms = "0" + parseInt(ms); } } this.el.innerHTML= this.format(dd,hh,mm,ss,ms); this.timer=setTimeout(function (){ self.second2Date.call(self); },self.showMS?10:1000) } } //测试 var d = new Date() d.setTime(d.getTime()+86400000*2+3600000*2+60000*5+1000*20); new Countdown( document.getElementById('CountdowTest01'), { time:d.getTime(), showMS:true } ) var d = new Date() d.setTime(d.getTime()+8888); new Countdown( document.getElementById('CountdowTest02'), { time:d.getTime() } ) </script> </body> </html>
运行代码