现在的位置: 首页 > 综合 > 正文

JS倒计时方法封装

2012年08月09日 ⁄ 综合 ⁄ 共 1895字 ⁄ 字号 评论关闭

今天公司新增加了一个活动页面(稍后把地址放出来大家抢购吧,哈哈),其中有类似于限时抢购的东西,本来要在网上找找这个小功能结果,大家都进行了编码(鄙视啊!),没办法自己整一个吧,放上来共享给需要的人

<div id="countdown" class="timer">
    <span id="days"></span><span id="hour"></span><span id="minute"></span><span id="second"></span></div>
<div id="countdown2" class="timer">
    <span id="days"></span><span id="hour"></span><span id="minute"></span><span id="second"></span></div>
<script type="text/javascript">
window.onload = function(){
    //实例化
    var oDiv = document.getElementById("countdown");
    var oneTime = new Clock(1337508688400,oDiv);
        oneTime.startCount();
    var oDiv2 = document.getElementById("countdown2");
    var oneTime2 = new Clock(1337508628400,oDiv2);
        oneTime2.startCount();
}
//声明类
function Clock(t,elem){
    //元素
    this.elems = elem.getElementsByTagName("span");
//控制器
    this.controller;
    this.setTimes = 100;
    this.endTime= new Date(t);
    //初始化时间
    this.day = 0;
    this.hour = 0;
    this.minute = 0;
    this.second = 0;
    this.Ms = 0;
}
//类方法
Clock.prototype={
    startCount:function(){
        var me = this;
        var NowTime = new Date();
        var time = me.endTime.getTime() - NowTime.getTime();
        if(time!=0 || time != null){
            if(parseInt(time) &&time>=0 ){
                //初始化
                me.showTime(time);    
                me.controller = setInterval(function(){
                    me.setTimeCount();
                },me.setTimes);
            }else{
                me.elemCreat();
            }
        }
    },
    setTimeCount:function(){
        var me = this;
        var time = me.endTime;
        if(time<=0){
            clearTimeout(me.controller);
            return;    
        }
        var NowTime = new Date();
        var now = time.getTime() - NowTime.getTime();
        me.showTime(now);    
    },
    showTime:function(time){
        this.day = Math.floor(time/(1000 * 60 * 60 * 24));
        this.hour = Math.floor(time/(1000*60*60)) % 24;
        this.minute = Math.floor(time/(1000*60)) % 60;
        this.second = Math.floor(time/1000) % 60;
        this.Ms = Math.floor(time/100) % 10;
        //
        this.elemCreat();
    },
    elemCreat:function(){
        var me = this;
        var second;
        if(me.second<=0){
            second = 0;
            me.second=0;
        }else{
            second = me.second+"."+me.Ms;
        }
        if(me.minute<=0){me.minute=0}
        if(me.hour<=0){me.hour=0}
        if(me.day<=0){me.day=0}
        //
        me.elems[3].innerHTML = second;
        me.elems[2].innerHTML = me.minute;
        me.elems[1].innerHTML = me.hour;
        me.elems[0].innerHTML = me.day;    
    }
};
</script>

 

抱歉!评论已关闭.