时间倒计时封装

基于jq的时间倒计时插件封装

一:jq插件的封装方式

(1)第一种方式

(function ($) {
    $.extend({
        say: function (name) {
             alert(name + ": hello");
        }
    });

})(jQuery);

//调用
$.say("meng");

(2)第二种方式

$.fn.extend({          
    alertClick:function() {            
          $(this).click(function(){                 
                 alert($(this).val());           
           });           
     }       
});       

//调用
$("#input1").alertClick();

二:基于以上知识,封装了一个简单的倒计时插件

/**
  * countDownTime.js
  * @param {Object} options
  * @param {String} options.date 日期
  * @param {dom} options.days 日的dom元素
  * @param {dom} options.hours 小时的dom元素
  * @param {dom} options.minutes 分钟的dom元素
  * @param {dom} options.seconds 秒的dom元素
  */

jQuery.fn.extend({

  countDownTime: function (options) {
    var a = this;
    var date = options.date,
        day = options.days,
        hour = options.hours,
        min = options.minutes,
        sec = options.seconds;

    var formatNumber = function (a) {
      if (a <= 0) {
        a = 0
      }
      return a = a.toString(),
          a[1] ? a : "0" + a
    };

    var formatTime = function (a, b) {
      switch (b) {
        case "day":
          return a / 1e3 / 60 / 60 / 24;
        case "hours":
          return a / 1e3 / 60 / 60 % 24;
        case "minutes":
          return a / 1e3 / 60 % 60;
        case "seconds":
          return a / 1e3 % 60
      }
    }

    var timer = function (a) {
      var b, c, d, e, f, g, h;
      b = new Date,
          c = new Date(date),
          d = c.getTime() - b.getTime(),
          e = Math.floor(formatTime(d, "day")),
          f = Math.floor(formatTime(d, "hours")),
          g = Math.floor(formatTime(d, "minutes")),
          h = Math.floor(formatTime(d, "seconds")),
      day && (day.innerText = formatNumber(e)),
      hour && (hour.innerText = formatNumber(f)),
      min && (min.innerText = formatNumber(g)),
      sec && (sec.innerText = formatNumber(h));
      if (e <= 0 && f <= 0 && g <= 0 && h <= 0) {
        clearInterval(timeI);
      }
    };

    var timeI = setInterval(timer, 1e3);

  }
});


00天 : 00时 : 00分 : 00

你可能感兴趣的:(js)