js倒计时

本文介绍了如何使用JavaScript进行倒计时的实现,通过获取服务器当前时间作为起点,进行时间的计算和显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

//倒计时的插件
$.fn.extend({
    oaoTime: function (nowTime) {
        this.each(function () {
            var dateStr = $(this).attr("end-date");
            var endDate = new Date(dateStr.replace(/-/g, "/"));//取得指定时间的总毫秒数
            //now是在动态页面中取得服务器的时间,如果没有定义使用客户端时间
             now = nowTime;
            if (nowTime == undefined) {
                now = new Date().getTime();
            }
            var tms = endDate - now;//得到时间差
            // if (tms < 0) {
            //     alert("时间过期了");
            //     return;
            // }
            $.oaoTime.timers.push({tms: tms, content: $(this)});
            $.oaoTime.start();
        });
    }
});
//倒计时的插件
$.oaoTime = {
    //倒计时容器,所有需要倒计时的时间都需要注册到这个容器中,容器中放的是一个object,object描述了倒计时的结束时间,以及显示时间的jquery对象(例如div)
    timers: [],
    //全局的一个倒计时状态,init表示初始化状态,start表示运行中状态,stop表示停止状态
    status: 'init',
    //计算时间并定时刷新时间的方法,本插件的核心代码
    takeCount: function () {
        //如果定时器没有启动不执行
        if (this.status != 'start') return;
        setTimeout("$.oaoTime.takeCount()", 1000);
        var timers = this.timers;
        for (var i = 0, j = timers.length; i < j; i++) {
            //计数减一
            timers[i].tms -= 1000;
            //console.info(timers[i].tms);
            //计算时分秒
            var days = Math.floor(timers[i].tms / (1000 * 60 * 60 * 24));
            var hours = Math.floor(timers[i].tms / (1000 * 60 * 60)) % 24;
            var minutes = Math.floor(timers[i].tms / (1000 * 60)) % 60;
            var seconds = Math.floor(timers[i].tms / 1000) % 60;
            if (days < 0) days = 0;
            if (hours < 0) hours = 0;
            if (minutes < 0) minutes = 0;
            if (seconds < 0) seconds = 0;
            var newTimeText = ((hours + days * 24)<=9?'0'+(hours + days * 24):(hours + days * 24)) + ":" + (minutes<=9?'0'+minutes:minutes) + ":" + (seconds<=9?'0'+seconds:seconds);
            timers[i].content.text(newTimeText);
            //console.info(newTimeText);
        }
    },
    //启动倒计时
    start: function () {
        if (this.status == 'init') {
            this.status = 'start';
            this.takeCount();
        }
    },
    //停止倒计时
    stop: function () {
        this.status = 'stop';
    }
};

调用:

 

<span class="pop-time-out" end-date="2018-07-26 18:35">00:00:00</span>
$('.pop-time-out')oaoTime(new Date())

new Date()可改为服务器当前时间

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值