bootstrap-datetimepicker源码解读

1.插件的使用

    单独输入框



$(".date_input").datetimepicker({
       language:  'zh-CN',
       autoclose: 1,
       minView: 2,
       maxView: 2,
       format:"dd"
});

    输入框加图标

$(".trigger_date_input").datetimepicker({ language: 'zh-CN', autoclose: 1, minView: 2, maxView: 2, format:"dd" });

   时间段

var startDate=$('#startTime').val()?$('#startTime').val():new Date();
	$('#startTime').datetimepicker({
        language: "zh-CN",
        format: "yyyy-mm-dd hh:ii",
        autoclose: true,
        todayBtn: true,
        minuteStep: 10,
        startDate:startDate
    }).on("click",function(){
        var endTime=$("#endTime").val();
        if ( endTime ){
            $("#startTime").datetimepicker("setEndDate",endTime);
        };
    });
    $('#endTime').datetimepicker({
        language: "zh-CN",
        format: "yyyy-mm-dd hh:ii",
        autoclose: true,
        todayBtn: true,
        minuteStep: 10
    }).on("click",function(){
        var startTime=$("#startTime").val();
        if ( startTime ){
            $("#endTime").datetimepicker("setStartDate",startTime);
        };
    });

    事件接口:show、hide、outOfRange(点击不可选的日期触发)、prev/next(左右箭头点击触发)、changeMonth、changeYear、changeMinute、changeHour、changeDay、changeDate、changeMode(时间选择器面板状态改变时触发)

 

2.插件的结构

Datetimepicker($ele,options)构造函数梳理配置项和执行初始化方法,prototype属性中写入方法、触发事件;

$.fn.datetimepicker构造插件时使用$this.data("datetimepicker",new Datetimepicker)执行初始化操作;

$.fn.datetimepicker.Constructor=Datetimepicker提供Datetimepicker构造函数的接口;

$.fn.datetimepicker.noConflict调用完成以后执行释放$.fn.datetimepicker。

Datetimepicker方法show、fill、update、setValue的拆分需要再领会。。。

 

3.新启示

$.map方法将数组作为jquery对象处理,执行遍历操作;

Date对象API操作;

var args = Array.apply(null, arguments);将arguments转化成真实数组输出;

Math.min方法促使某值自加1的时候不至于超过限定值,Math.max设置最小为0;

绑定事件通过通过数组、$.on({click:$.proxy(fn,object),keyup:$.proxy(fn,object)})的形式达成;

$.proxy(fn,object)首先将函数fn赋给DOM元素的事件,其次将该函数的上下文改变成object;

$.trigger({type:"show",date:this.date})方法传入触发事件类型以及相应的参数,提供事件接口。

 

!function ($) {

  // Add ECMA262-5 Array methods if not supported natively (IE8)
  if (!('indexOf' in Array.prototype)) {
    Array.prototype.indexOf = function (find, i) {
      if (i === undefined) i = 0;
      if (i < 0) i += this.length;
      if (i < 0) i = 0;
      for (var n = this.length; i < n; i++) {
        if (i in this && this[i] === find) {
          return i;
        }
      }
      return -1;
    }
  }

  function elementOrParentIsFixed (element) {
    var $element = $(element);
    var $checkElements = $element.add($element.parents());// add方法将元素添加到jquery对象中
    var isFixed = false;
    $checkElements.each(function(){
      if ($(this).css('position') === 'fixed') {
        isFixed = true;
        return false;
      }
    });
    return isFixed;
  }

  // new Date()返回Tue Mar 08 2016 14:00:03 GMT+0800形式时间;
  // Date对象的UTC方法返回从1970年1月1号开始的毫秒数;
  function UTCDate() {
    return new Date(Date.UTC.apply(Date, arguments));
  }

  function UTCToday() {
    var today = new Date();
    return UTCDate(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate(), today.getUTCHours(), today.getUTCMinutes(), today.getUTCSeconds(), 0);
  }

  // Picker object
  // this.element触发元素,this.picker时间选择器
  // 配置项:用户定义的优先,Datetimepicker方法中的options配置以及.datetimepicker元素的data数据,其次是默认的配置项
  //        this.lanuage语言包配置在dates=$.fn.datetimepicker.dates中,通过$.fn.datetimepicker.dates['zh-CN']添加配置;
  //        this.formatType日期数据格式类型,有php、standard两种;
  //        this.format日期数据格式,如yyyy-mm-dd;
  //        this.isInline是否内嵌;this.isVisible是否可见;
  //        this.isInput触发元素是单个输入框的形式,还是输入框加图标的形式;
  //        this.fontAwesome设置为true时使用fontAweSome图标,否则使用bootstrap自带的图标;
  //        this.bootcssVer检查bootstrap版本,影响样式类的名称;
  //        this.component当触发元素为输入框加图标的形式,需要加date样式,this.component设置成图标的父级span;
  //        this.componentReset重置图标;
  //        this.linkField链接域,用户选择的日期也反映在该链接域中;
  //        this.linkFormat链接域的日期格式;
  //        this.minuteStep时间选择器分钟面板设置两个邻近的时间相差多少分钟;
  //        this.pickerPosition时间选择器显示位置设置;
  //        this.showMeridian显示时间是以pm/am的形式展现,还是用:00的形式;
  //        this.initialDate设置初始时间,也可以在输入框中直接设置日期值,被update方法调用更新显示日期;
  //        this.zIndex设置zindex值;
  //        this.icons设置左右箭头的样式类,template.replace方法更换模板的样式类;
  //        this.icontype左右箭头样式类型;
  //        this.clickedOutside点击日期输入框外区域,隐藏日期时间选择器;
  //        this.formatViewType为time时,调用getFormattedDate方法使时间选择器的标题栏日期为用户设置的日期格式,否则显示语言包配置的月份、日期;
  //   (默认设置一方面三目运算符实现,另一方面通过顺序执行的条件语句实现)
  //        this.minView、this.maxView配置时间选择器面板的精确范围,可以是文字值或数字值,DPGlobal.convertViewMode方法统一改为数字值;
  //        this.wheelViewModeNavigation是否开启鼠标滚轮事件;
  //        this.wheelViewModeNavigationInverseDirection鼠标滚轮反向操作;
  //        this.wheelViewModeNavigationDelay鼠标滚轮延迟事件,this.wheelPause为真时,延迟时间内不触发滚轮事件;
  //        this.startViewMode时间选择器初始视图,默认为datetimepicker-days选择日期,同时改变viewMode值;
  //        this.selectView设置时间选择器点击效果改变显示时间从年月日面板的哪个状态开始,如selectView=4时点击年份选择面板,
  //    输入框即将日期显示出来; 
  //        this.forceParse为真时,通过update、fill方法将用户初始日期配置转化时间格式后,显示在时间选择器面板上,
  //    或者通过hide、setValue将时间选择器点击选中的值输出到输入框;
  //        template赋值为DPGlobal里设置的模板变量,再使用replace方法将图标变量替换成真实值,构成时间选择器;
  //        this.picker赋值为时间选择器模板,并将该模板添加到输入框后面,再绑定事件;
  //        this.isRTL左右箭头位置是否互换;
  //        this.autoclose时间选择器面板点击事件发生以后是否隐藏面板;
  //        this.keyboardNavigation键盘左右箭头敲击时是否使时间选择器跳转;
  //        this.todayBtn今天按钮是否显示;this.todayHighlight今天按钮是否高亮;
  //        this.weekStart设置一周以星期几起始;this.weekEnd设置一周以星期几结束;
  //        this.startDate默认负无限;this.endDate设置结束日期;
  //        this.setStartDate设置开始日期,使用update方法更新、填充面板;
  //        this.setEndDate设置结束日期,使用update方法更新、填充面板;
  //        this.daysOfWeekDisabled/this.setDaysOfWeekDisabled设置一周中不可选择的日期;
  //        this.setMinutesDisabled、this.setHoursDisabled设置时间选择器面板不可选的分钟、时钟;
  //        
  //        执行方法:
  //        this._attachEvents()绑定事件;
  //        $(document).on('mousedown', this.clickedOutside)点击其他区域隐藏时间选择器面板;
  //        this.fillDow()设置时间选择器面板星期一栏的显示状况;
  //        this.fillMonths()填充月份选择面板中月份;
  //        this.update()若设置了开始日期,将其显示在时间选择器中,调用fill方法填充时间选择器面板;
  //        this.showMode()设置面板初始显示状态,调用updateNavArrows方法更新左右箭头;
  //        this.show()当时间选择器面板内嵌时,开始时显示。  
  var Datetimepicker = function (element, options) {
    var that = this;

    this.element = $(element);

    // add container for single page application
    // when page switch the datetimepicker div will be removed also.
    this.container = options.container || 'body';

    this.language = options.language || this.element.data('date-language') || 'en';
    this.language = this.language in dates ? this.language : this.language.split('-')[0]; // fr-CA fallback to fr
    this.language = this.language in dates ? this.language : 'en';
    this.isRTL = dates[this.language].rtl || false;

    this.formatType = options.formatType || this.element.data('format-type') || 'standard';
    this.format = DPGlobal.parseFormat(options.format || this.element.data('date-format') || dates[this.language].format || DPGlobal.getDefaultFormat(this.formatType, 'input'), this.formatType);
    
    this.isInline = false;
    this.isVisible = false;

    this.isInput = this.element.is('input');

    this.fontAwesome = options.fontAwesome || this.element.data('font-awesome') || false;

    this.bootcssVer = options.bootcssVer || (this.isInput ? (this.element.is('.form-control') ? 3 : 2) : ( this.bootcssVer = this.element.is('.input-group') ? 3 : 2 ));

    // this.component当输入框旁有日历、事件图标时设置
    // this.componentReset当输入框旁有重置图标时设置
    this.component = this.element.is('.date') ? ( this.bootcssVer == 3 ? this.element.find('.input-group-addon .glyphicon-th, .input-group-addon .glyphicon-time, .input-group-addon .glyphicon-calendar, .input-group-addon .fa-calendar, .input-group-addon .fa-clock-o').parent() : this.element.find('.add-on .icon-th, .add-on .icon-time, .add-on .icon-calendar, .add-on .fa-calendar, .add-on .fa-clock-o').parent()) : false;
    this.componentReset = this.element.is('.date') ? ( this.bootcssVer == 3 ? this.element.find('.input-group-addon .glyphicon-remove, .input-group-addon .fa-times').parent():this.element.find('.add-on .icon-remove, .add-on .fa-times').parent()) : false;
    this.hasInput = this.component && this.element.find('input').length;
    if (this.component && this.component.length === 0) {
      this.component = false;
    }

    this.linkField = options.linkField || this.element.data('link-field') || false;
    this.linkFormat = DPGlobal.parseFormat(options.linkFormat || this.element.data('link-format') || DPGlobal.getDefaultFormat(this.formatType, 'link'), this.formatType);
    
    this.minuteStep = options.minuteStep || this.element.data('minute-step') || 5;

    this.pickerPosition = options.pickerPosition || this.element.data('picker-position') || 'bottom-right';

    this.showMeridian = options.showMeridian || this.element.data('show-meridian') || false;

    this.initialDate = options.initialDate || new Date();

    this.zIndex = options.zIndex || this.element.data('z-index') || undefined;

    this.icons = {
      leftArrow: this.fontAwesome ? 'fa-arrow-left' : (this.bootcssVer === 3 ? 'glyphicon-arrow-left' : 'icon-arrow-left'),
      rightArrow: this.fontAwesome ? 'fa-arrow-right' : (this.bootcssVer === 3 ? 'glyphicon-arrow-right' : 'icon-arrow-right')
    }
    this.icontype = this.fontAwesome ? 'fa' : 'glyphicon';

    // 绑定事件
    this._attachEvents();

    // 点击日期输入框外区域,隐藏日期时间选择器
    this.clickedOutside = function (e) {
        if ($(e.target).closest('.datetimepicker').length === 0) {// closest从当前元素开始,逐级往上寻找
            that.hide();
        }
    }

    // this.formatViewType为time时,调用getFormattedDate方法使时间选择器的标题栏日期为用户设置的日期格式,否则显示语言包配置的月份、日期
    this.formatViewType = 'datetime';
    if ('formatViewType' in options) {
      this.formatViewType = options.formatViewType;
    } else if ('formatViewType' in this.element.data()) {
      this.formatViewType = this.element.data('formatViewType');
    }

    // 设置时间选择器面板的精确范围,DPGlobal.convertViewMode将数字值、文字值改为数字值
    this.minView = 0;
    if ('minView' in options) {
      this.minView = options.minView;
    } else if ('minView' in this.element.data()) {
      this.minView = this.element.data('min-view');
    }
    this.minView = DPGlobal.convertViewMode(this.minView);

    this.maxView = DPGlobal.modes.length - 1;
    if ('maxView' in options) {
      this.maxView = options.maxView;
    } else if ('maxView' in this.element.data()) {
      this.maxView = this.element.data('max-view');
    }
    this.maxView = DPGlobal.convertViewMode(this.maxView);

    this.wheelViewModeNavigation = false;
    if ('wheelViewModeNavigation' in options) {
      this.wheelViewModeNavigation = options.wheelViewModeNavigation;
    } else if ('wheelViewModeNavigation' in this.element.data()) {
      this.wheelViewModeNavigation = this.element.data('view-mode-wheel-navigation');
    }

    this.wheelViewModeNavigationInverseDirection = false;
    if ('wheelViewModeNavigationInverseDirection' in options) {
      this.wheelViewModeNavigationInverseDirection = options.wheelViewModeNavigationInverseDirection;
    } else if ('wheelViewModeNavigationInverseDirection' in this.element.data()) {
      this.wheelViewModeNavigationInverseDirection = this.element.data('view-mode-wheel-navigation-inverse-dir');
    }

    this.wheelViewModeNavigationDelay = 100;
    if ('wheelViewModeNavigationDelay' in options) {
      this.wheelViewModeNavigationDelay = options.wheelViewModeNavigationDelay;
    } else if ('wheelViewModeNavigationDelay' in this.element.data()) {
      this.wheelViewModeNavigationDelay = this.element.data('view-mode-wheel-navigation-delay');
    }

    this.startViewMode = 2;
    if ('startView' in options) {
      this.startViewMode = options.startView;
    } else if ('startView' in this.element.data()) {
      this.startViewMode = this.element.data('start-view');
    }
    this.startViewMode = DPGlobal.convertViewMode(this.startViewMode);
    this.viewMode = this.startViewMode;

    this.viewSelect = this.minView;
    if ('viewSelect' in options) {
      this.viewSelect = options.viewSelect;
    } else if ('viewSelect' in this.element.data()) {
      this.viewSelect = this.element.data('view-select');
    }
    this.viewSelect = DPGlobal.convertViewMode(this.viewSelect);

    this.forceParse = true;
    if ('forceParse' in options) {
      this.forceParse = options.forceParse;
    } else if ('dateForceParse' in this.element.data()) {
      this.forceParse = this.element.data('date-force-parse');
    }

    // template赋值为DPGlobal里设置的模板变量,再使用replace方法将图标变量替换成真实值,构成时间选择器
    var template = this.bootcssVer === 3 ? DPGlobal.templateV3 : DPGlobal.template;
    while (template.indexOf('{iconType}') !== -1) {
      template = template.replace('{iconType}', this.icontype);
    }
    while (template.indexOf('{leftArrow}') !== -1) {
      template = template.replace('{leftArrow}', this.icons.leftArrow);
    }
    while (template.indexOf('{rightArrow}') !== -1) {
      template = template.replace('{rightArrow}', this.icons.rightArrow);
    }

    // this.picker赋值为时间选择器模板,并将该模板添加到输入框后面,再绑定事件
    this.picker = $(template)
      .appendTo(this.isInline ? this.element : this.container) // 'body')
      .on({
        click:     $.proxy(this.click, this),
        mousedown: $.proxy(this.mousedown, this)
      });

    // 若浏览器支持鼠标滚轮事件,则绑定鼠标滚轮事件,否则抛出异常
    if (this.wheelViewModeNavigation) {
      if ($.fn.mousewheel) {
        this.picker.on({mousewheel: $.proxy(this.mousewheel, this)});
      } else {
        console.log('Mouse Wheel event is not supported. Please include the jQuery Mouse Wheel plugin before enabling this option');
      }
    }

    // 时间选择器面板是否内嵌,
    if (this.isInline) {
      this.picker.addClass('datetimepicker-inline');
    } else {
      this.picker.addClass('datetimepicker-dropdown-' + this.pickerPosition + ' dropdown-menu');
    }

    if (this.isRTL) {
      this.picker.addClass('datetimepicker-rtl');
      var selector = this.bootcssVer === 3 ? '.prev span, .next span' : '.prev i, .next i';
      this.picker.find(selector).toggleClass(this.icons.leftArrow + ' ' + this.icons.rightArrow);
    }

    $(document).on('mousedown', this.clickedOutside);

    this.autoclose = false;
    if ('autoclose' in options) {
      this.autoclose = options.autoclose;
    } else if ('dateAutoclose' in this.element.data()) {
      this.autoclose = this.element.data('date-autoclose');
    }

    this.keyboardNavigation = true;
    if ('keyboardNavigation' in options) {
      this.keyboardNavigation = options.keyboardNavigation;
    } else if ('dateKeyboardNavigation' in this.element.data()) {
      this.keyboardNavigation = this.element.data('date-keyboard-navigation');
    }

    this.todayBtn = (options.todayBtn || this.element.data('date-today-btn') || false);
    this.todayHighlight = (options.todayHighlight || this.element.data('date-today-highlight') || false);

    this.weekStart = ((options.weekStart || this.element.data('date-weekstart') || dates[this.language].weekStart || 0) % 7);
    this.weekEnd = ((this.weekStart + 6) % 7);

    this.startDate = -Infinity;
    this.endDate = Infinity;

    this.daysOfWeekDisabled = [];

    this.setStartDate(options.startDate || this.element.data('date-startdate'));
    this.setEndDate(options.endDate || this.element.data('date-enddate'));

    this.setDaysOfWeekDisabled(options.daysOfWeekDisabled || this.element.data('date-days-of-week-disabled'));

    this.setMinutesDisabled(options.minutesDisabled || this.element.data('date-minute-disabled'));
    this.setHoursDisabled(options.hoursDisabled || this.element.data('date-hour-disabled'));

    this.fillDow();
    this.fillMonths();

    this.update();
    this.showMode();

    if (this.isInline) {
      this.show();
    }
  };

  Datetimepicker.prototype = {
    constructor: Datetimepicker,

    _events:       [],

    /*
    * _attachEvents绑定事件,一种是单一输入框的形式,另一种是输入框加图标的形式component;
    *       this._events记录绑定元素,绑定事件以及方法、上下文;
    ****** (绑定事件通过通过数组、$.on({click:$.proxy(fn,object),keyup:$.proxy(fn,object)})的形式达成)
    ****** ($.proxy(fn,object)首先将函数fn赋给DOM元素的事件,其次将该函数的上下文改变成object)
    * _detachEvents解绑事件,仍旧以元素加事件函数的形式解绑;
    * show调用place方法调整时间选择器位置,update方法更新时间选择器显示内容,时间选择器当前状态为可见;
    ****** ($.trigger({type:"show",date:this.date})方法传入触发事件类型以及相应的参数)
    * hide隐藏时间选择器面板,当forceParse设为真时,使用setValue输入框中时间格式不对的数值转化成正确格式,showMode方法将时间选择器的初始状态重设为startView设置值;
    * remove移除时间选择器面板,同时document解除点击其余区域隐藏时间选择器事件;
    * getDate调用getUTCDate方法获取格林威治时间修正后的this.date日期;
    * getUTCDate返回this.date日期;
    * setDate调用setUTCDate方法设置格林威治时间修正后的this.date值;
    * setUTCDate当日期在startDate和endDate之间,将参数d设置为this.date,输入框设置为该值,调用fill填充时间选择器,否则触发超出范围事件;
    * setFormat设置this.format时间格式的值,并调用setValue填充输入框;
    * setValue将输入框的值填充为格式化成format形式后的时间值,并且关联域linkField也作相应改变;
    * getFormattedDate将utc格式的时间转化成format格式的时间;
    * setStartDate设置开始时间,并调用update、updateNavArrows更新时间选择器面板可选时间显示情况;
    * setEndDate设置结束时间,并调用update、updateNavArrows更新时间选择器面板可选时间显示情况;
    * setDaysOfWeekDisabled设置星期中不可选的日期,并调用update、updateNavArrows更新时间选择器面板可选时间显示情况;
    ****** ($([1,2,3]).map方法将普通数组作为jquery对象遍历并过滤数组处理)
    * setMinutesDisabled设置不可选的分钟,并调用update、updateNavArrows更新时间选择器面板可选时间显示情况;
    * setHoursDisabled设置不可选的小时,并调用update、updateNavArrows更新时间选择器面板可选时间显示情况;
    * place设置时间选择器的zIndex、left、top值等定位相关数据;
    * update当用户在输入框设置了date值,取该值为this.date,输入框填充该值,否则取当前日期为this.date,调用fill方法填充时间选择器;
    * fillDow设置时间选择器日期选择面板的星期栏目,以weekStart起始,一周循环结束,如显示"Su,Mo,Tu,We,Th,Fr,Sa";
    * fillMonth设置时间选择器月份选择面板的月份栏目,将date[this.language].monthsShort中配置项显示在页面中;
    * fill填充时间选择器标题栏的日期,根据配置项显示today按钮,调用updateNavArrows、fillMonth方法填充可选月份以及左右箭头显示状况;
    *       日期面板循环prevMonth填充日期选择面板,循环填充时钟选择面板,循环按this.minuteStep填充分钟选择面板;
    *       fillMonth方法填充月份选择面板,根据startMonth、endMonth、startYear、endYear为月份添加active、disabled样式;
    *       填充年选择面板,十年范围内;调用place方法调整时间选择器位置;
    * updateNavArrows根据时间选择器面板上日期等的可选择性设置显示或隐藏左右箭头;
    ****** ($.toggle方法中直接传入判断表达式,成立时显示,否则隐藏)
    * mousewheel鼠标滚轮改变时间选择器面板状态,通过调用showMode方法改变时间选择器面板年月日显示状态;
    * click时间选择器面板点击前进后退按钮改变面板显示内容,调用moveMonth、moveHour等方法,并触发事件以供调用;
    *       点击today按钮设置date日期,并且重置时间选择器面板状态;
    *       点击年月日时分按钮调用Date对象的方法设置date日期,并改变时间选择器面板状态,由年月日时分高位向低位走,并触发事件以供调用;
    ****** ($(ele).trigger()触发事件,提供事件接口,以供插件使用者使用$.on方法调用) 
    ****** (使用Date对象更新设置date日期,调用setUTCMonth、getUTCMonth设置获取日期) 
    * _setDate设置this.date和this.viewDate,刷新时间选择器面板并填充输入框,触发change事件;
    * moveMinute、moveHour、moveDate使分钟、小时、日期增1或减1,返回新的日期值给viewDate;
    * moveMonth当dir为1或-1时,月份,加1或减1,test函数测试对月份的改动是否成功,不成功则反复执行日期减1、月份重新设置,
    *       当dir不为1或-1时,通过自调用使month反复+1或-1得到新的月份,再重写该月份是否符合条件,否则天数减1。
    * moveYear调用moveMonth函数使年份增1或减1,返回新的日期值给viewDate;
    * dateWithinRange判断日期是否在startDate、endDate范围内;
    * keydown键盘操作功能相应实现;
    * showMode传入参数dir,改变时间选择器面板状态viewMode,没有dir时不改变viewMode,并调用updateNavArrows设置左右箭头的可见性,
    *       当viewMode改变时,通过DPGlobal.modes[this.viewMode]显示时间选择器年月日面板,对应关系是:
    *       0(hour):datetimepicker-minutes面板、1(day):datetimepicker-hours面板、2(month):datetimepicker-days面板、
    *       3(year):datetimepicker-months面板、4(decade):datetimepicker-years面板;
    ****** (Math.min方法促使某值自加1的时候不至于超过限定值,Math.max设置最小为0)
    * reset重置date日期为空;
    * convertViewModeText面板状态由数字值0,1,2,3,4返回文字值hour,day,month,year,decade等。
     */

    _attachEvents: function () {
      this._detachEvents();
      if (this.isInput) {
        // 使用$.proxy方法将作用域改变成this,this不就是当前的dom元素吗???
        this._events = [
          [this.element, {
            focus:   $.proxy(this.show, this),
            keyup:   $.proxy(this.update, this),
            keydown: $.proxy(this.keydown, this)
          }]
        ];
      }
      else if (this.component && this.hasInput) {
        this._events = [
          [this.element.find('input'), {
            focus:   $.proxy(this.show, this),
            keyup:   $.proxy(this.update, this),
            keydown: $.proxy(this.keydown, this)
          }],
          [this.component, {
            click: $.proxy(this.show, this)
          }]
        ];
        if (this.componentReset) {
          this._events.push([
            this.componentReset,
            {click: $.proxy(this.reset, this)}
          ]);
        }
      }
      else if (this.element.is('div')) { 
        this.isInline = true;
      }
      else {
        this._events = [
          [this.element, {
            click: $.proxy(this.show, this)
          }]
        ];
      }
      for (var i = 0, el, ev; i < this._events.length; i++) {
        el = this._events[i][0];
        ev = this._events[i][1];
        el.on(ev);
      }
    },

    _detachEvents: function () {
      for (var i = 0, el, ev; i < this._events.length; i++) {
        el = this._events[i][0];
        ev = this._events[i][1];
        el.off(ev);
      }
      this._events = [];
    },

    show: function (e) {
      this.picker.show();
      this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
      if (this.forceParse) {
        this.update();
      }
      this.place();
      $(window).on('resize', $.proxy(this.place, this));
      if (e) {
        e.stopPropagation();
        e.preventDefault();
      }
      this.isVisible = true;
      this.element.trigger({
        type: 'show',
        date: this.date
      });
    },

    hide: function (e) {
      if (!this.isVisible) return;
      if (this.isInline) return;
      this.picker.hide();
      $(window).off('resize', this.place);
      this.viewMode = this.startViewMode;
      this.showMode();
      if (!this.isInput) {
        $(document).off('mousedown', this.hide);
      }

      if (
        this.forceParse &&
          (
            this.isInput && this.element.val() ||
              this.hasInput && this.element.find('input').val()
            )
        )
        this.setValue();
      this.isVisible = false;
      this.element.trigger({
        type: 'hide',
        date: this.date
      });
    },

    remove: function () {
      this._detachEvents();
      $(document).off('mousedown', this.clickedOutside);
      this.picker.remove();
      delete this.picker;
      delete this.element.data().datetimepicker;
    },

    getDate: function () {
      var d = this.getUTCDate();
      return new Date(d.getTime() + (d.getTimezoneOffset() * 60000));
    },

    getUTCDate: function () {
      return this.date;
    },

    setDate: function (d) {
      this.setUTCDate(new Date(d.getTime() - (d.getTimezoneOffset() * 60000)));
    },

    setUTCDate: function (d) {
      if (d >= this.startDate && d <= this.endDate) {
        this.date = d;
        this.setValue();
        this.viewDate = this.date;
        this.fill();
      } else {
        this.element.trigger({
          type:      'outOfRange',
          date:      d,
          startDate: this.startDate,
          endDate:   this.endDate
        });
      }
    },

    setFormat: function (format) {
      this.format = DPGlobal.parseFormat(format, this.formatType);
      var element;
      if (this.isInput) {
        element = this.element;
      } else if (this.component) {
        element = this.element.find('input');
      }
      if (element && element.val()) {
        this.setValue();
      }
    },

    setValue: function () {
      var formatted = this.getFormattedDate();
      if (!this.isInput) {
        if (this.component) {
          this.element.find('input').val(formatted);
        }
        this.element.data('date', formatted);
      } else {
        this.element.val(formatted);
      }
      if (this.linkField) {
        $('#' + this.linkField).val(this.getFormattedDate(this.linkFormat));
      }
    },

    getFormattedDate: function (format) {
      if (format == undefined) format = this.format;
      return DPGlobal.formatDate(this.date, format, this.language, this.formatType);
    },

    setStartDate: function (startDate) {
      this.startDate = startDate || -Infinity;
      if (this.startDate !== -Infinity) {
        this.startDate = DPGlobal.parseDate(this.startDate, this.format, this.language, this.formatType);
      }
      this.update();
      this.updateNavArrows();
    },

    setEndDate: function (endDate) {
      this.endDate = endDate || Infinity;
      if (this.endDate !== Infinity) {
        this.endDate = DPGlobal.parseDate(this.endDate, this.format, this.language, this.formatType);
      }
      this.update();
      this.updateNavArrows();
    },

    setDaysOfWeekDisabled: function (daysOfWeekDisabled) {
      this.daysOfWeekDisabled = daysOfWeekDisabled || [];
      if (!$.isArray(this.daysOfWeekDisabled)) {
        this.daysOfWeekDisabled = this.daysOfWeekDisabled.split(/,\s*/);
      }
      this.daysOfWeekDisabled = $.map(this.daysOfWeekDisabled, function (d) {
        return parseInt(d, 10);
      });
      this.update();
      this.updateNavArrows();
    },

    setMinutesDisabled: function (minutesDisabled) {
      this.minutesDisabled = minutesDisabled || [];
      if (!$.isArray(this.minutesDisabled)) {
        this.minutesDisabled = this.minutesDisabled.split(/,\s*/);
      }
      this.minutesDisabled = $.map(this.minutesDisabled, function (d) {
        return parseInt(d, 10);
      });
      this.update();
      this.updateNavArrows();
    },

    setHoursDisabled: function (hoursDisabled) {
      this.hoursDisabled = hoursDisabled || [];
      if (!$.isArray(this.hoursDisabled)) {
        this.hoursDisabled = this.hoursDisabled.split(/,\s*/);
      }
      this.hoursDisabled = $.map(this.hoursDisabled, function (d) {
        return parseInt(d, 10);
      });
      this.update();
      this.updateNavArrows();
    },

    place: function () {
      if (this.isInline) return;

      // zIndex取div中最大的zIndex属性外加10
      if (!this.zIndex) {
        var index_highest = 0;
        $('div').each(function () {
          var index_current = parseInt($(this).css('zIndex'), 10);
          if (index_current > index_highest) {
            index_highest = index_current;
          }
        });
        this.zIndex = index_highest + 10;
      }

      // 定位时间选择器
      var offset, top, left, containerOffset;
      if (this.container instanceof $) {
        containerOffset = this.container.offset();
      } else {
        containerOffset = $(this.container).offset();
      }

      if (this.component) {
        offset = this.component.offset();
        left = offset.left;
        if (this.pickerPosition == 'bottom-left' || this.pickerPosition == 'top-left') {
          left += this.component.outerWidth() - this.picker.outerWidth();
        }
      } else {
        offset = this.element.offset();
        left = offset.left;
      }

      var bodyWidth = document.body.clientWidth || window.innerWidth;
      if (left + 220 > bodyWidth) {
        left = bodyWidth - 220;
      }

      if (this.pickerPosition == 'top-left' || this.pickerPosition == 'top-right') {
        top = offset.top - this.picker.outerHeight();
      } else {
        top = offset.top + this.height;
      }

      top = top - containerOffset.top;
      left = left - containerOffset.left;

      this.picker.css({
        top:    top,
        left:   left,
        zIndex: this.zIndex
      });
    },

    update: function () {
      var date, fromArgs = false;
      if (arguments && arguments.length && (typeof arguments[0] === 'string' || arguments[0] instanceof Date)) {
        date = arguments[0];
        fromArgs = true;
      } else {
        date = (this.isInput ? this.element.val() : this.element.find('input').val()) || this.element.data('date') || this.initialDate;
        if (typeof date == 'string' || date instanceof String) {
          date = date.replace(/^\s+|\s+$/g,'');
        }
      }

      if (!date) {
        date = new Date();
        fromArgs = false;
      }

      this.date = DPGlobal.parseDate(date, this.format, this.language, this.formatType);

      if (fromArgs) this.setValue();

      if (this.date < this.startDate) {
        this.viewDate = new Date(this.startDate);
      } else if (this.date > this.endDate) {
        this.viewDate = new Date(this.endDate);
      } else {
        this.viewDate = new Date(this.date);
      }
      this.fill();
    },

    fillDow: function () {
      var dowCnt = this.weekStart,
        html = '';
      while (dowCnt < this.weekStart + 7) {
        html += '' + dates[this.language].daysMin[(dowCnt++) % 7] + '';
      }
      html += '';
      this.picker.find('.datetimepicker-days thead').append(html);
    },

    fillMonths: function () {
      var html = '',
        i = 0;
      while (i < 12) {
        html += '' + dates[this.language].monthsShort[i++] + '';
      }
      this.picker.find('.datetimepicker-months td').html(html);
    },

    fill: function () {
      if (this.date == null || this.viewDate == null) {
        return;
      }
      var d = new Date(this.viewDate),
        year = d.getUTCFullYear(),
        month = d.getUTCMonth(),
        dayMonth = d.getUTCDate(),
        hours = d.getUTCHours(),
        minutes = d.getUTCMinutes(),
        startYear = this.startDate !== -Infinity ? this.startDate.getUTCFullYear() : -Infinity,
        startMonth = this.startDate !== -Infinity ? this.startDate.getUTCMonth() + 1 : -Infinity,
        endYear = this.endDate !== Infinity ? this.endDate.getUTCFullYear() : Infinity,
        endMonth = this.endDate !== Infinity ? this.endDate.getUTCMonth() + 1 : Infinity,
        currentDate = (new UTCDate(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate())).valueOf(),
        today = new Date();
      // 填充标题栏当前年与月
      this.picker.find('.datetimepicker-days thead th:eq(1)')
        .text(dates[this.language].months[month] + ' ' + year);
      if (this.formatViewType == 'time') {
        var formatted = this.getFormattedDate();
        this.picker.find('.datetimepicker-hours thead th:eq(1)').text(formatted);
        this.picker.find('.datetimepicker-minutes thead th:eq(1)').text(formatted);
      } else {
        this.picker.find('.datetimepicker-hours thead th:eq(1)')
          .text(dayMonth + ' ' + dates[this.language].months[month] + ' ' + year);
        this.picker.find('.datetimepicker-minutes thead th:eq(1)')
          .text(dayMonth + ' ' + dates[this.language].months[month] + ' ' + year);
      }
      // 显示或隐藏today按钮,toggle方法中直接传入判断表达式
      this.picker.find('tfoot th.today')
        .text(dates[this.language].today)
        .toggle(this.todayBtn !== false);
      this.updateNavArrows();
      this.fillMonths();
      /*var prevMonth = UTCDate(year, month, 0,0,0,0,0);
       prevMonth.setUTCDate(prevMonth.getDate() - (prevMonth.getUTCDay() - this.weekStart + 7)%7);*/
      // 获取上月在时间选择器面板上遗留下的最后一组星期数,prevMonth设置为该星期的第一天,nextMonth在该值的基础上+42;
      var prevMonth = UTCDate(year, month - 1, 28, 0, 0, 0, 0),
        day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
      prevMonth.setUTCDate(day);
      prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.weekStart + 7) % 7);
      var nextMonth = new Date(prevMonth);
      nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
      nextMonth = nextMonth.valueOf();
      // 填充日期,当prevMonth小于nextMonth,开启循环自加1,填充时间选择器日期选择面板
      var html = [];
      var clsName;
      while (prevMonth.valueOf() < nextMonth) {
        if (prevMonth.getUTCDay() == this.weekStart) {
          html.push('');
        }
        clsName = '';
        if (prevMonth.getUTCFullYear() < year || (prevMonth.getUTCFullYear() == year && prevMonth.getUTCMonth() < month)) {
          clsName += ' old';
        } else if (prevMonth.getUTCFullYear() > year || (prevMonth.getUTCFullYear() == year && prevMonth.getUTCMonth() > month)) {
          clsName += ' new';
        }
        // Compare internal UTC date with local today, not UTC today
        if (this.todayHighlight &&
          prevMonth.getUTCFullYear() == today.getFullYear() &&
          prevMonth.getUTCMonth() == today.getMonth() &&
          prevMonth.getUTCDate() == today.getDate()) {
          clsName += ' today';
        }
        if (prevMonth.valueOf() == currentDate) {
          clsName += ' active';
        }
        if ((prevMonth.valueOf() + 86400000) <= this.startDate || prevMonth.valueOf() > this.endDate ||
          $.inArray(prevMonth.getUTCDay(), this.daysOfWeekDisabled) !== -1) {
          clsName += ' disabled';
        }
        html.push('' + prevMonth.getUTCDate() + '');
        if (prevMonth.getUTCDay() == this.weekEnd) {
          html.push('');
        }
        prevMonth.setUTCDate(prevMonth.getUTCDate() + 1);
      }
      this.picker.find('.datetimepicker-days tbody').empty().append(html.join(''));

      // 填充时,showMeridian为真时,时钟加上am、pm字符,否则加上:00显示
      html = [];
      var txt = '', meridian = '', meridianOld = '';
      var hoursDisabled = this.hoursDisabled || [];
      for (var i = 0; i < 24; i++) {
        if (hoursDisabled.indexOf(i) !== -1) continue;
        var actual = UTCDate(year, month, dayMonth, i);
        clsName = '';
        // We want the previous hour for the startDate
        if ((actual.valueOf() + 3600000) <= this.startDate || actual.valueOf() > this.endDate) {
          clsName += ' disabled';
        } else if (hours == i) {
          clsName += ' active';
        }
        if (this.showMeridian && dates[this.language].meridiem.length == 2) {
          meridian = (i < 12 ? dates[this.language].meridiem[0] : dates[this.language].meridiem[1]);
          if (meridian != meridianOld) {
            if (meridianOld != '') {
              html.push('');
            }
            html.push('
' + meridian.toUpperCase() + ''); } meridianOld = meridian; txt = (i % 12 ? i % 12 : 12); html.push('' + txt + ''); if (i == 23) { html.push('
'); } } else { txt = i + ':00'; html.push('' + txt + ''); } } this.picker.find('.datetimepicker-hours td').html(html.join('')); // 按this.minuteStep填充分钟 html = []; txt = '', meridian = '', meridianOld = ''; var minutesDisabled = this.minutesDisabled || []; for (var i = 0; i < 60; i += this.minuteStep) { if (minutesDisabled.indexOf(i) !== -1) continue; var actual = UTCDate(year, month, dayMonth, hours, i, 0); clsName = ''; if (actual.valueOf() < this.startDate || actual.valueOf() > this.endDate) { clsName += ' disabled'; } else if (Math.floor(minutes / this.minuteStep) == Math.floor(i / this.minuteStep)) { clsName += ' active'; } if (this.showMeridian && dates[this.language].meridiem.length == 2) { meridian = (hours < 12 ? dates[this.language].meridiem[0] : dates[this.language].meridiem[1]); if (meridian != meridianOld) { if (meridianOld != '') { html.push(''); } html.push('
' + meridian.toUpperCase() + ''); } meridianOld = meridian; txt = (hours % 12 ? hours % 12 : 12); //html.push(''+txt+''); html.push('' + txt + ':' + (i < 10 ? '0' + i : i) + ''); if (i == 59) { html.push('
'); } } else { txt = i + ':00'; //html.push(''+txt+''); html.push('' + hours + ':' + (i < 10 ? '0' + i : i) + ''); } } this.picker.find('.datetimepicker-minutes td').html(html.join('')); // fillMonth方法填充月份选择面板,根据startMonth、endMonth、startYear、endYear为月份添加active、disabled样式 var currentYear = this.date.getUTCFullYear(); var months = this.picker.find('.datetimepicker-months') .find('th:eq(1)') .text(year) .end() .find('span').removeClass('active'); if (currentYear == year) { // getUTCMonths() returns 0 based, and we need to select the next one // To cater bootstrap 2 we don't need to select the next one var offset = months.length - 12; months.eq(this.date.getUTCMonth() + offset).addClass('active'); } if (year < startYear || year > endYear) { months.addClass('disabled'); } if (year == startYear) { months.slice(0, startMonth + 1).addClass('disabled'); } if (year == endYear) { months.slice(endMonth).addClass('disabled'); } // 填充年选择面板,十年范围内 html = ''; year = parseInt(year / 10, 10) * 10; var yearCont = this.picker.find('.datetimepicker-years') .find('th:eq(1)') .text(year + '-' + (year + 9)) .end() .find('td'); year -= 1; for (var i = -1; i < 11; i++) { html += '' + year + ''; year += 1; } yearCont.html(html); this.place(); }, updateNavArrows: function () { var d = new Date(this.viewDate), year = d.getUTCFullYear(), month = d.getUTCMonth(), day = d.getUTCDate(), hour = d.getUTCHours(); switch (this.viewMode) { case 0: if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear() && month <= this.startDate.getUTCMonth() && day <= this.startDate.getUTCDate() && hour <= this.startDate.getUTCHours()) { this.picker.find('.prev').css({visibility: 'hidden'}); } else { this.picker.find('.prev').css({visibility: 'visible'}); } if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear() && month >= this.endDate.getUTCMonth() && day >= this.endDate.getUTCDate() && hour >= this.endDate.getUTCHours()) { this.picker.find('.next').css({visibility: 'hidden'}); } else { this.picker.find('.next').css({visibility: 'visible'}); } break; case 1: if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear() && month <= this.startDate.getUTCMonth() && day <= this.startDate.getUTCDate()) { this.picker.find('.prev').css({visibility: 'hidden'}); } else { this.picker.find('.prev').css({visibility: 'visible'}); } if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear() && month >= this.endDate.getUTCMonth() && day >= this.endDate.getUTCDate()) { this.picker.find('.next').css({visibility: 'hidden'}); } else { this.picker.find('.next').css({visibility: 'visible'}); } break; case 2: if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear() && month <= this.startDate.getUTCMonth()) { this.picker.find('.prev').css({visibility: 'hidden'}); } else { this.picker.find('.prev').css({visibility: 'visible'}); } if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear() && month >= this.endDate.getUTCMonth()) { this.picker.find('.next').css({visibility: 'hidden'}); } else { this.picker.find('.next').css({visibility: 'visible'}); } break; case 3: case 4: if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear()) { this.picker.find('.prev').css({visibility: 'hidden'}); } else { this.picker.find('.prev').css({visibility: 'visible'}); } if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear()) { this.picker.find('.next').css({visibility: 'hidden'}); } else { this.picker.find('.next').css({visibility: 'visible'}); } break; } }, mousewheel: function (e) { e.preventDefault(); e.stopPropagation(); if (this.wheelPause) { return; } this.wheelPause = true; var originalEvent = e.originalEvent; var delta = originalEvent.wheelDelta;// event.wheelDelta判断鼠标滚轮是向上滚动还是向下滚动 var mode = delta > 0 ? 1 : (delta === 0) ? 0 : -1; if (this.wheelViewModeNavigationInverseDirection) { mode = -mode; } this.showMode(mode); setTimeout($.proxy(function () { this.wheelPause = false }, this), this.wheelViewModeNavigationDelay); }, click: function (e) { e.stopPropagation(); e.preventDefault(); var target = $(e.target).closest('span, td, th, legend'); if (target.is('.' + this.icontype)) { target = $(target).parent().closest('span, td, th, legend'); } if (target.length == 1) { if (target.is('.disabled')) { this.element.trigger({ type: 'outOfRange', date: this.viewDate, startDate: this.startDate, endDate: this.endDate }); return; } // 时间选择器面板th标题栏左右箭头和礼拜几标识, switch (target[0].nodeName.toLowerCase()) { case 'th': switch (target[0].className) { case 'switch': this.showMode(1); break; case 'prev': case 'next': // navStep遇年为10,其他情况为1,通过moveHour、moveDate、moveMonth、moveYear更新viewDate var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className == 'prev' ? -1 : 1); // this.viewMode为0,时间选择器展示datetimepicker-minutes面板,viewModeText是hour,点击next按钮hour+1; // this.viewMode为1,时间选择器展示datetimepicker-hours面板,viewModeText是day,点击next按钮day+1; // this.viewMode为2,时间选择器展示datetimepicker-days面板,viewModeText是month,点击next按钮month+1; // this.viewMode为3,时间选择器展示datetimepicker-months面板,viewModeText是year,点击next按钮year+1; // this.viewMode为4,时间选择器展示datetimepicker-years面板,viewModeText是decade,点击next按钮year+10; switch (this.viewMode) { case 0: this.viewDate = this.moveHour(this.viewDate, dir); break; case 1: this.viewDate = this.moveDate(this.viewDate, dir); break; case 2: this.viewDate = this.moveMonth(this.viewDate, dir); break; case 3: case 4: this.viewDate = this.moveYear(this.viewDate, dir); break; } this.fill(); this.element.trigger({ type: target[0].className + ':' + this.convertViewModeText(this.viewMode), date: this.viewDate, startDate: this.startDate, endDate: this.endDate }); break; case 'today': var date = new Date(); date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), 0); // Respect startDate and endDate. if (date < this.startDate) date = this.startDate; else if (date > this.endDate) date = this.endDate; // 重置时间选择器面板viewMode为初始值,设置date日期,填充时间选择器面板 this.viewMode = this.startViewMode; this.showMode(0); this._setDate(date); this.fill(); if (this.autoclose) { this.hide(); } break; } break; case 'span': if (!target.is('.disabled')) { var year = this.viewDate.getUTCFullYear(), month = this.viewDate.getUTCMonth(), day = this.viewDate.getUTCDate(), hours = this.viewDate.getUTCHours(), minutes = this.viewDate.getUTCMinutes(), seconds = this.viewDate.getUTCSeconds(); if (target.is('.month')) { this.viewDate.setUTCDate(1); // $(selector).index(element)获得element元素相对选择器selector的index位置 month = target.parent().find('span').index(target); day = this.viewDate.getUTCDate(); this.viewDate.setUTCMonth(month); this.element.trigger({ type: 'changeMonth', date: this.viewDate }); if (this.viewSelect >= 3) { this._setDate(UTCDate(year, month, day, hours, minutes, seconds, 0)); } } else if (target.is('.year')) { this.viewDate.setUTCDate(1); year = parseInt(target.text(), 10) || 0; this.viewDate.setUTCFullYear(year); this.element.trigger({ type: 'changeYear', date: this.viewDate }); if (this.viewSelect >= 4) { this._setDate(UTCDate(year, month, day, hours, minutes, seconds, 0)); } } else if (target.is('.hour')) { hours = parseInt(target.text(), 10) || 0; if (target.hasClass('hour_am') || target.hasClass('hour_pm')) { if (hours == 12 && target.hasClass('hour_am')) { hours = 0; } else if (hours != 12 && target.hasClass('hour_pm')) { hours += 12; } } this.viewDate.setUTCHours(hours); this.element.trigger({ type: 'changeHour', date: this.viewDate }); if (this.viewSelect >= 1) { this._setDate(UTCDate(year, month, day, hours, minutes, seconds, 0)); } } else if (target.is('.minute')) { minutes = parseInt(target.text().substr(target.text().indexOf(':') + 1), 10) || 0; this.viewDate.setUTCMinutes(minutes); this.element.trigger({ type: 'changeMinute', date: this.viewDate }); if (this.viewSelect >= 0) { this._setDate(UTCDate(year, month, day, hours, minutes, seconds, 0)); } } if (this.viewMode != 0) { var oldViewMode = this.viewMode; // showMode改变时间选择器面板viewMode状态值,由高位向低位走,即year面板到month面板 this.showMode(-1); this.fill(); if (oldViewMode == this.viewMode && this.autoclose) { this.hide(); } } else { this.fill(); if (this.autoclose) { this.hide(); } } } break; case 'td': if (target.is('.day') && !target.is('.disabled')) { var day = parseInt(target.text(), 10) || 1; var year = this.viewDate.getUTCFullYear(), month = this.viewDate.getUTCMonth(), hours = this.viewDate.getUTCHours(), minutes = this.viewDate.getUTCMinutes(), seconds = this.viewDate.getUTCSeconds(); if (target.is('.old')) { if (month === 0) { month = 11; year -= 1; } else { month -= 1; } } else if (target.is('.new')) { if (month == 11) { month = 0; year += 1; } else { month += 1; } } this.viewDate.setUTCFullYear(year); this.viewDate.setUTCMonth(month, day); this.element.trigger({ type: 'changeDay', date: this.viewDate }); if (this.viewSelect >= 2) { this._setDate(UTCDate(year, month, day, hours, minutes, seconds, 0)); } } var oldViewMode = this.viewMode; this.showMode(-1); this.fill(); if (oldViewMode == this.viewMode && this.autoclose) { this.hide(); } break; } } }, _setDate: function (date, which) { if (!which || which == 'date') this.date = date; if (!which || which == 'view') this.viewDate = date; this.fill(); this.setValue(); var element; if (this.isInput) { element = this.element; } else if (this.component) { element = this.element.find('input'); } if (element) { element.change(); if (this.autoclose && (!which || which == 'date')) { //this.hide(); } } this.element.trigger({ type: 'changeDate', date: this.date }); if(date == null) this.date = this.viewDate; }, moveMinute: function (date, dir) { if (!dir) return date; var new_date = new Date(date.valueOf()); //dir = dir > 0 ? 1 : -1; new_date.setUTCMinutes(new_date.getUTCMinutes() + (dir * this.minuteStep)); return new_date; }, moveHour: function (date, dir) { if (!dir) return date; var new_date = new Date(date.valueOf()); //dir = dir > 0 ? 1 : -1; new_date.setUTCHours(new_date.getUTCHours() + dir); return new_date; }, moveDate: function (date, dir) { if (!dir) return date; var new_date = new Date(date.valueOf()); //dir = dir > 0 ? 1 : -1; new_date.setUTCDate(new_date.getUTCDate() + dir); return new_date; }, moveMonth: function (date, dir) { if (!dir) return date; var new_date = new Date(date.valueOf()), day = new_date.getUTCDate(), month = new_date.getUTCMonth(), mag = Math.abs(dir), new_month, test; dir = dir > 0 ? 1 : -1; if (mag == 1) { test = dir == -1 // If going back one month, make sure month is not current month // (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02) ? function () { return new_date.getUTCMonth() == month; } // If going forward one month, make sure month is as expected // (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02) // Date对象的setUTCMonth方法将1月31号设置为2月时,返回的日期是3月2号,不是2月31号 : function () { return new_date.getUTCMonth() != new_month; }; new_month = month + dir; new_date.setUTCMonth(new_month); // Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11 if (new_month < 0 || new_month > 11) new_month = (new_month + 12) % 12; } else { // For magnitudes >1, move one month at a time... for (var i = 0; i < mag; i++) // ...which might decrease the day (eg, Jan 31 to Feb 28, etc)... new_date = this.moveMonth(new_date, dir); // ...then reset the day, keeping it in the new month new_month = new_date.getUTCMonth(); new_date.setUTCDate(day); test = function () { return new_month != new_date.getUTCMonth(); }; } // Common date-resetting loop -- if date is beyond end of month, make it // end of month while (test()) { new_date.setUTCDate(--day); new_date.setUTCMonth(new_month); } return new_date; }, moveYear: function (date, dir) { return this.moveMonth(date, dir * 12); }, dateWithinRange: function (date) { return date >= this.startDate && date <= this.endDate; }, keydown: function (e) { if (this.picker.is(':not(:visible)')) { if (e.keyCode == 27) // allow escape to hide and re-show picker this.show(); return; } var dateChanged = false, dir, day, month, newDate, newViewDate; switch (e.keyCode) { case 27: // escape this.hide(); e.preventDefault(); break; case 37: // left case 39: // right if (!this.keyboardNavigation) break; dir = e.keyCode == 37 ? -1 : 1; viewMode = this.viewMode; if (e.ctrlKey) { viewMode += 2; } else if (e.shiftKey) { viewMode += 1; } if (viewMode == 4) { newDate = this.moveYear(this.date, dir); newViewDate = this.moveYear(this.viewDate, dir); } else if (viewMode == 3) { newDate = this.moveMonth(this.date, dir); newViewDate = this.moveMonth(this.viewDate, dir); } else if (viewMode == 2) { newDate = this.moveDate(this.date, dir); newViewDate = this.moveDate(this.viewDate, dir); } else if (viewMode == 1) { newDate = this.moveHour(this.date, dir); newViewDate = this.moveHour(this.viewDate, dir); } else if (viewMode == 0) { newDate = this.moveMinute(this.date, dir); newViewDate = this.moveMinute(this.viewDate, dir); } if (this.dateWithinRange(newDate)) { this.date = newDate; this.viewDate = newViewDate; this.setValue(); this.update(); e.preventDefault(); dateChanged = true; } break; case 38: // up case 40: // down if (!this.keyboardNavigation) break; dir = e.keyCode == 38 ? -1 : 1; viewMode = this.viewMode; if (e.ctrlKey) { viewMode += 2; } else if (e.shiftKey) { viewMode += 1; } if (viewMode == 4) { newDate = this.moveYear(this.date, dir); newViewDate = this.moveYear(this.viewDate, dir); } else if (viewMode == 3) { newDate = this.moveMonth(this.date, dir); newViewDate = this.moveMonth(this.viewDate, dir); } else if (viewMode == 2) { newDate = this.moveDate(this.date, dir * 7); newViewDate = this.moveDate(this.viewDate, dir * 7); } else if (viewMode == 1) { if (this.showMeridian) { newDate = this.moveHour(this.date, dir * 6); newViewDate = this.moveHour(this.viewDate, dir * 6); } else { newDate = this.moveHour(this.date, dir * 4); newViewDate = this.moveHour(this.viewDate, dir * 4); } } else if (viewMode == 0) { newDate = this.moveMinute(this.date, dir * 4); newViewDate = this.moveMinute(this.viewDate, dir * 4); } if (this.dateWithinRange(newDate)) { this.date = newDate; this.viewDate = newViewDate; this.setValue(); this.update(); e.preventDefault(); dateChanged = true; } break; case 13: // enter if (this.viewMode != 0) { var oldViewMode = this.viewMode; this.showMode(-1); this.fill(); if (oldViewMode == this.viewMode && this.autoclose) { this.hide(); } } else { this.fill(); if (this.autoclose) { this.hide(); } } e.preventDefault(); break; case 9: // tab this.hide(); break; } if (dateChanged) { var element; if (this.isInput) { element = this.element; } else if (this.component) { element = this.element.find('input'); } if (element) { element.change(); } this.element.trigger({ type: 'changeDate', date: this.date }); } }, showMode: function (dir) { if (dir) { // 使用Math.min方法以使this.viewMode自加1的时候,不至于超过DPGlobal.modes的长度,Math.max设置最小为0 var newViewMode = Math.max(0, Math.min(DPGlobal.modes.length - 1, this.viewMode + dir)); if (newViewMode >= this.minView && newViewMode <= this.maxView) { this.element.trigger({ type: 'changeMode', date: this.viewDate, oldViewMode: this.viewMode, newViewMode: newViewMode }); this.viewMode = newViewMode; } } /* vitalets: fixing bug of very special conditions: jquery 1.7.1 + webkit + show inline datetimepicker in bootstrap popover. Method show() does not set display css correctly and datetimepicker is not shown. Changed to .css('display', 'block') solve the problem. See https://github.com/vitalets/x-editable/issues/37 In jquery 1.7.2+ everything works fine. */ //this.picker.find('>div').hide().filter('.datetimepicker-'+DPGlobal.modes[this.viewMode].clsName).show(); this.picker.find('>div').hide().filter('.datetimepicker-' + DPGlobal.modes[this.viewMode].clsName).css('display', 'block'); this.updateNavArrows(); }, reset: function (e) { this._setDate(null, 'date'); }, convertViewModeText: function (viewMode) { switch (viewMode) { case 4: return 'decade'; case 3: return 'year'; case 2: return 'month'; case 1: return 'day'; case 0: return 'hour'; } } }; // bootstrap-datetimepicker插件在$.fn.datetimepicker赋值之后调用,用old记录,使用$.fn.datetimepicker.noConflict回到old var old = $.fn.datetimepicker; $.fn.datetimepicker = function (option) { // fn.apply(object,array):object调用fn的方法,array作为参数 // var args = Array.apply(null, arguments);将arguments转化成真实数组输出 var args = Array.apply(null, arguments); args.shift();// option参数中首项有效,其余均无效 var internal_return; this.each(function () { var $this = $(this), data = $this.data('datetimepicker'), options = typeof option == 'object' && option; if (!data) { // data("property",object)方法可以为属性添加对象,不会显示在页面中,但可以用data方法获取 // 插件:$.fn.plugin=new plugin或$this.data("plugin",new plugin)??? $this.data('datetimepicker', (data = new Datetimepicker(this, $.extend({}, $.fn.datetimepicker.defaults, options)))); } // internal_return用来作什么用途??? if (typeof option == 'string' && typeof data[option] == 'function') { internal_return = data[option].apply(data, args); if (internal_return !== undefined) { return false; } } }); if (internal_return !== undefined) return internal_return; else return this; }; $.fn.datetimepicker.defaults = { }; $.fn.datetimepicker.Constructor = Datetimepicker; var dates = $.fn.datetimepicker.dates = { en: { days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], daysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], daysMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'], months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], meridiem: ['am', 'pm'], suffix: ['st', 'nd', 'rd', 'th'], today: 'Today' } }; /* * isLeapYear判断是否闰年; * getDaysInMonth通过数组的形式获取月中含有的天数; * getDefaultFormat默认的时间格式,分为标准的和php形式的两种,其中php形式为Y-M-D; * validParts判断时间格式的正则表达式; * nonpunctuation选取非标点符号的字符,比如yyyy-mm-dd或yyyy:mm:dd中的yyyy、mm、dd; * parseFormat将时间格式拆分为分隔符和年月日时分各部分,第一个参数是yy-mm-dd,第二个参数是时间格式是标准类型还是php类型; * (match将匹配到的元素以数组的形式输出) * parseDate通过format设定的时间格式将2014-07-11形式或者2014-January-11,12:00am的date转化成utc格式的时间; * ($([1,2,3])将[1,2,3]作为jquery对象处理,可以使用filter方法,this指代当前的数组元素) * formatDate将utc格式的时间输出为format格式的时间数据; * convertViewMode调整时间选择器面板的年月日显示状况; * headTemplate、headTemplateV3、contTemplate、footTemplate时间选择器子模板,V3标记bootstrap3; * template、templateV3时间选择器模板。 * * 时间选择器面板状态切换由datetimepicker-years、datetimepicker-months、datetimepicker-days、datetimepicker-hours、datetimepicker-minutes显示隐藏状态构成。 */ var DPGlobal = { modes: [ { clsName: 'minutes', navFnc: 'Hours', navStep: 1 }, { clsName: 'hours', navFnc: 'Date', navStep: 1 }, { clsName: 'days', navFnc: 'Month', navStep: 1 }, { clsName: 'months', navFnc: 'FullYear', navStep: 1 }, { clsName: 'years', navFnc: 'FullYear', navStep: 10 } ], isLeapYear: function (year) { return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) }, getDaysInMonth: function (year, month) { return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] }, getDefaultFormat: function (type, field) { if (type == 'standard') { if (field == 'input') return 'yyyy-mm-dd hh:ii'; else return 'yyyy-mm-dd hh:ii:ss'; } else if (type == 'php') { if (field == 'input') return 'Y-m-d H:i'; else return 'Y-m-d H:i:s'; } else { throw new Error('Invalid format type.'); } }, validParts: function (type) { if (type == 'standard') { return /hh?|HH?|p|P|ii?|ss?|dd?|DD?|mm?|MM?|yy(?:yy)?/g; } else if (type == 'php') { return /[dDjlNwzFmMnStyYaABgGhHis]/g; } else { throw new Error('Invalid format type.'); } }, nonpunctuation: /[^ -\/:-@\[-`{-~\t\n\rTZ]+/g, parseFormat: function (format, type) { // IE treats \0 as a string end in inputs (truncating the value), // so it's a bad format delimiter, anyway var separators = format.replace(this.validParts(type), '\0').split('\0'), parts = format.match(this.validParts(type));// match以数组形式获取匹配值 if (!separators || !separators.length || !parts || parts.length == 0) { throw new Error('Invalid date format.'); } return {separators: separators, parts: parts}; }, parseDate: function (date, format, language, type) { if (date instanceof Date) { var dateUTC = new Date(date.valueOf() - date.getTimezoneOffset() * 60000); dateUTC.setMilliseconds(0); return dateUTC; } if (/^\d{4}\-\d{1,2}\-\d{1,2}$/.test(date)) { format = this.parseFormat('yyyy-mm-dd', type); } if (/^\d{4}\-\d{1,2}\-\d{1,2}[T ]\d{1,2}\:\d{1,2}$/.test(date)) { format = this.parseFormat('yyyy-mm-dd hh:ii', type); } if (/^\d{4}\-\d{1,2}\-\d{1,2}[T ]\d{1,2}\:\d{1,2}\:\d{1,2}[Z]{0,1}$/.test(date)) { format = this.parseFormat('yyyy-mm-dd hh:ii:ss', type); } if (/^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$/.test(date)) { var part_re = /([-+]\d+)([dmwy])/, parts = date.match(/([-+]\d+)([dmwy])/g), part, dir; date = new Date(); for (var i = 0; i < parts.length; i++) { part = part_re.exec(parts[i]);// exec以数组形式获取()内的匹配值 dir = parseInt(part[1]); switch (part[2]) { case 'd': date.setUTCDate(date.getUTCDate() + dir);// 根据当前时间增加或减少日期??? break; case 'm': date = Datetimepicker.prototype.moveMonth.call(Datetimepicker.prototype, date, dir);// ??? break; case 'w': date.setUTCDate(date.getUTCDate() + dir * 7); break; case 'y': date = Datetimepicker.prototype.moveYear.call(Datetimepicker.prototype, date, dir); break; } } return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), 0); } var parts = date && date.toString().match(this.nonpunctuation) || [],// &&值取后者,||值取前者 date = new Date(0, 0, 0, 0, 0, 0, 0), parsed = {}, setters_order = ['hh', 'h', 'ii', 'i', 'ss', 's', 'yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'D', 'DD', 'd', 'dd', 'H', 'HH', 'p', 'P'], setters_map = { hh: function (d, v) { return d.setUTCHours(v); }, h: function (d, v) { return d.setUTCHours(v); }, HH: function (d, v) { return d.setUTCHours(v == 12 ? 0 : v); }, H: function (d, v) { return d.setUTCHours(v == 12 ? 0 : v); }, ii: function (d, v) { return d.setUTCMinutes(v); }, i: function (d, v) { return d.setUTCMinutes(v); }, ss: function (d, v) { return d.setUTCSeconds(v); }, s: function (d, v) { return d.setUTCSeconds(v); }, yyyy: function (d, v) { return d.setUTCFullYear(v); }, yy: function (d, v) { return d.setUTCFullYear(2000 + v); }, m: function (d, v) { v -= 1; while (v < 0) v += 12; v %= 12; d.setUTCMonth(v); while (d.getUTCMonth() != v) if (isNaN(d.getUTCMonth())) return d; else d.setUTCDate(d.getUTCDate() - 1); return d; }, d: function (d, v) { return d.setUTCDate(v); }, p: function (d, v) { return d.setUTCHours(v == 1 ? d.getUTCHours() + 12 : d.getUTCHours()); } }, val, filtered, part; setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m']; setters_map['dd'] = setters_map['d']; setters_map['P'] = setters_map['p']; date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()); // parts以标点符号拆分获得数字值,format.parts以yyyy、mm、dd拆分获得格式值 if (parts.length == format.parts.length) { for (var i = 0, cnt = format.parts.length; i < cnt; i++) { val = parseInt(parts[i], 10); part = format.parts[i]; if (isNaN(val)) { switch (part) { case 'MM': // dates[language].months=['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] // date中带有January及相似字样时,截取months数组中的元素作匹配比较,返回符合元素的index序号 filtered = $(dates[language].months).filter(function () { var m = this.slice(0, parts[i].length), p = parts[i].slice(0, m.length); return m == p; }); val = $.inArray(filtered[0], dates[language].months) + 1; break; case 'M': filtered = $(dates[language].monthsShort).filter(function () { var m = this.slice(0, parts[i].length), p = parts[i].slice(0, m.length); return m.toLowerCase() == p.toLowerCase(); }); val = $.inArray(filtered[0], dates[language].monthsShort) + 1; break; case 'p': case 'P': // date中带有am或pm字样时,其中带pm字样时相应的小时数据加上12,am不变 val = $.inArray(parts[i].toLowerCase(), dates[language].meridiem); break; } } parsed[part] = val; } for (var i = 0, s; i < setters_order.length; i++) { s = setters_order[i]; if (s in parsed && !isNaN(parsed[s])) setters_map[s](date, parsed[s]) } } return date; }, formatDate: function (date, format, language, type) { if (date == null) { return ''; } var val; if (type == 'standard') { val = { // year yy: date.getUTCFullYear().toString().substring(2), yyyy: date.getUTCFullYear(), // month m: date.getUTCMonth() + 1, M: dates[language].monthsShort[date.getUTCMonth()], MM: dates[language].months[date.getUTCMonth()], // day d: date.getUTCDate(), D: dates[language].daysShort[date.getUTCDay()], DD: dates[language].days[date.getUTCDay()], p: (dates[language].meridiem.length == 2 ? dates[language].meridiem[date.getUTCHours() < 12 ? 0 : 1] : ''), // hour h: date.getUTCHours(), // minute i: date.getUTCMinutes(), // second s: date.getUTCSeconds() }; if (dates[language].meridiem.length == 2) { val.H = (val.h % 12 == 0 ? 12 : val.h % 12); } else { val.H = val.h; } val.HH = (val.H < 10 ? '0' : '') + val.H; val.P = val.p.toUpperCase(); val.hh = (val.h < 10 ? '0' : '') + val.h; val.ii = (val.i < 10 ? '0' : '') + val.i; val.ss = (val.s < 10 ? '0' : '') + val.s; val.dd = (val.d < 10 ? '0' : '') + val.d; val.mm = (val.m < 10 ? '0' : '') + val.m; } else if (type == 'php') { // php format val = { // year y: date.getUTCFullYear().toString().substring(2), Y: date.getUTCFullYear(), // month F: dates[language].months[date.getUTCMonth()], M: dates[language].monthsShort[date.getUTCMonth()], n: date.getUTCMonth() + 1, t: DPGlobal.getDaysInMonth(date.getUTCFullYear(), date.getUTCMonth()), // day j: date.getUTCDate(), l: dates[language].days[date.getUTCDay()], D: dates[language].daysShort[date.getUTCDay()], w: date.getUTCDay(), // 0 -> 6 N: (date.getUTCDay() == 0 ? 7 : date.getUTCDay()), // 1 -> 7 S: (date.getUTCDate() % 10 <= dates[language].suffix.length ? dates[language].suffix[date.getUTCDate() % 10 - 1] : ''), // hour a: (dates[language].meridiem.length == 2 ? dates[language].meridiem[date.getUTCHours() < 12 ? 0 : 1] : ''), g: (date.getUTCHours() % 12 == 0 ? 12 : date.getUTCHours() % 12), G: date.getUTCHours(), // minute i: date.getUTCMinutes(), // second s: date.getUTCSeconds() }; val.m = (val.n < 10 ? '0' : '') + val.n; val.d = (val.j < 10 ? '0' : '') + val.j; val.A = val.a.toString().toUpperCase(); val.h = (val.g < 10 ? '0' : '') + val.g; val.H = (val.G < 10 ? '0' : '') + val.G; val.i = (val.i < 10 ? '0' : '') + val.i; val.s = (val.s < 10 ? '0' : '') + val.s; } else { throw new Error('Invalid format type.'); } var date = [], seps = $.extend([], format.separators); for (var i = 0, cnt = format.parts.length; i < cnt; i++) { if (seps.length) { date.push(seps.shift()); } date.push(val[format.parts[i]]); } if (seps.length) { date.push(seps.shift()); } return date.join(''); }, convertViewMode: function (viewMode) { switch (viewMode) { case 4: case 'decade': viewMode = 4; break; case 3: case 'year': viewMode = 3; break; case 2: case 'month': viewMode = 2; break; case 1: case 'day': viewMode = 1; break; case 0: case 'hour': viewMode = 0; break; } return viewMode; }, // 通过replace方法将template中的{leftArrow}转变为真实值 headTemplate: '' + '' + '' + '' + '' + '' + '', headTemplateV3: '' + '' + ' ' + '' + ' ' + '' + '', contTemplate: '', footTemplate: '' }; DPGlobal.template = '
' + '
' + '' + DPGlobal.headTemplate + DPGlobal.contTemplate + DPGlobal.footTemplate + '
' + '
' + '
' + '' + DPGlobal.headTemplate + DPGlobal.contTemplate + DPGlobal.footTemplate + '
' + '
' + '
' + '' + DPGlobal.headTemplate + '' + DPGlobal.footTemplate + '
' + '
' + '
' + '' + DPGlobal.headTemplate + DPGlobal.contTemplate + DPGlobal.footTemplate + '
' + '
' + '
' + '' + DPGlobal.headTemplate + DPGlobal.contTemplate + DPGlobal.footTemplate + '
' + '
' + '
'; DPGlobal.templateV3 = '
' + '
' + '' + DPGlobal.headTemplateV3 + DPGlobal.contTemplate + DPGlobal.footTemplate + '
' + '
' + '
' + '' + DPGlobal.headTemplateV3 + DPGlobal.contTemplate + DPGlobal.footTemplate + '
' + '
' + '
' + '' + DPGlobal.headTemplateV3 + '' + DPGlobal.footTemplate + '
' + '
' + '
' + '' + DPGlobal.headTemplateV3 + DPGlobal.contTemplate + DPGlobal.footTemplate + '
' + '
' + '
' + '' + DPGlobal.headTemplateV3 + DPGlobal.contTemplate + DPGlobal.footTemplate + '
' + '
' + '
'; $.fn.datetimepicker.DPGlobal = DPGlobal; /* DATETIMEPICKER NO CONFLICT * =================== */ $.fn.datetimepicker.noConflict = function () { $.fn.datetimepicker = old; return this; }; /* DATETIMEPICKER DATA-API * ================== */ $(document).on( 'focus.datetimepicker.data-api click.datetimepicker.data-api', '[data-provide="datetimepicker"]', function (e) { var $this = $(this); if ($this.data('datetimepicker')) return; e.preventDefault(); // component click requires us to explicitly show it $this.datetimepicker('show'); } ); $(function () { $('[data-provide="datetimepicker-inline"]').datetimepicker(); }); }(window.jQuery);

 

你可能感兴趣的:(bootstrap,javascript,php)