倒计时插件

很简洁的一个倒计时插件  代码更简洁。

调用:

$("#test").Timedown(
                {
                    format: "<span>day天</span><span>hours时</span><span>minutes分<span/><span>seconds秒<span/>",
                    startTime: "2012/12/6 6:00:00",
                    endTime: "2012/12/6 6:00:10",
                    endTimeHtml: "倒计时结束了",//倒计时结束后显示结果  例如:小喇叭广播开始啦!
                    timerEndBlackFun: function () { alert("小喇叭广播开始啦"); }
                });

源码:

; (function ($) {
    $.fn.Timedown = function (userOption) {
        var option = {
            format: "<span>day天</span><span>hours时</span><span>minutes分<span/><span>seconds秒<span/>",//自定义显示时间结构 注意可以加样式哦  注意:day hours等等是占位符
            startTime: "",//开始时间"2012/12/6 6:00:00",
            endTime: "",//结束时间"2012/12/6 6:00:00",
            seconds: "",//秒数  当这里有值的时候 忽略startTime  endTime
            endTimeHtml: "",//倒计时结束后显示结果  例如:小喇叭广播开始啦!
            timerEndBlackFun: function () { }//回调函数
        }
        var options = $.extend({}, option, userOption || {});

        var nMS = new Date(options.endTime) - new Date(options.startTime);
        if (options.seconds > 0) {
            nMS = options.seconds * 1000;
        } else if (nMS > 0) {

        } else {
            options.timerEndBlackFun();
            return;
        }

        var $this = $(this); 
        var times = function () {
            nMS -= 1000;
            if (nMS <= 0) {
                clearInterval(_timeout);
                $this.html(options.endTimeHtml);
                options.timerEndBlackFun.call(this);
                return false;
            }
            var nD = Math.floor(nMS / (1000 * 60 * 60 * 24));
            var nH = Math.floor(nMS / (1000 * 60 * 60)) % 24;
            var nM = Math.floor(nMS / (1000 * 60)) % 60;
            var nS = Math.floor(nMS / 1000) % 60;

            var timesHtml = options.format;
            timesHtml = timesHtml.replace("day", nD);
            timesHtml = timesHtml.replace("hours", nH);
            timesHtml = timesHtml.replace("minutes", nM);
            timesHtml = timesHtml.replace("seconds", nS);

            $this.html(timesHtml);
        }
        var _timeout = setInterval(times, 1000);
    }
})(jQuery);
原文地址:https://www.cnblogs.com/bbvi/p/3254463.html