jQuery 倒计时插件

效果展示

倒计时

在线预览

倒计时在线预览

结构

<div class="count-down" data-end="2097/11/10">
    <p>90年后倒计时</p>
    <span class="day">0</span><span class="hour">0</span><span class="minute">0</span><span class="sec">0</span></div>
<div class="count-down a2" data-end="2018/02/16">
    <p>2018年春节倒计时</p>
    <span class="day">0</span><span class="hour">0</span><span class="minute">0</span><span class="sec">0</span></div>

js

  /*
    * @author: jingwei.wang
    * @time: 2017-11-09 15:21
    * @last modify time: 2017-11-10 11:01
    */
    (function ($) {
        $.fn.extend({
            countDown: function (options) {
                var defaults = {
                        endTime: '2097/11/10',  //结束时间,90年后
                        day: '.day',
                        hour: '.hour',
                        minute: '.minute',
                        sec: '.sec'
                    },
                    opts = $.extend({}, defaults, options); //对象扩展到opts
                this.each(function () {     //遍历
                    var $this = $(this);
                    times();    //先执行一次,防止刷新时数字都显示为0
                    var timer = setInterval(times, 1000);   //定时器执行

                    function times() {
                        var nowDate = new Date(),
                            endDate = $this.data('end') ? new Date($this.data('end')) : new Date(opts.endTime),// 定义了两种方式,data-end和defaults.endTime,优先data-end
                            tms = endDate - nowDate,    //时间差
                            days = Math.floor(tms / 1000 / 60 / 60 / 24),
                            hours = Math.floor(tms / 1000 / 60 / 60 % 24),
                            minutes = Math.floor(tms / 1000 / 60 % 60),
                            secs = Math.floor(tms / 1000 % 60);
                        if (tms > 0) {  //如果时间差大于0,显示倒计时
                            $this.find(opts.day).text(addZero(days));
                            $this.find(opts.hour).text(addZero(hours));
                            $this.find(opts.minute).text(addZero(minutes));
                            $this.find(opts.sec).text(addZero(secs));
                        } else {    //否则清除定时器,倒计时结束
                            clearInterval(timer);
                        }
                    }
                });


                function addZero(t) {  //一位数加0
                    if (t < 10) {
                        return t = '0' + t;
                    } else {
                        return t;
                    }
                }
                return this; //返回this方便链式调用
            }
        });
        $('.count-down').countDown(); //默认调用方法
        $('.a2').countDown();
    })(jQuery)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值