读bootstrap modal.js

保留下来自己看的时候的注释 ,以便将来自己学习使用
若有不正确之处,请指正,一起学习

/* ========================================================================
 * Bootstrap: modal.js v3.3.7
 * http://getbootstrap.com/javascript/#modals
 * ========================================================================
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // MODAL CLASS DEFINITION
  // ======================

  var Modal = function (element, options) {
    // element --> 弹框层
    this.options             = options
    this.$body               = $(document.body)
    this.$element            = $(element) // jQuery 对象
    this.$dialog             = this.$element.find('.modal-dialog')
    this.$backdrop           = null // 半透明背景层
    this.isShown             = null
    this.originalBodyPad     = null
    this.scrollbarWidth      = 0
    this.ignoreBackdropClick = false

    // ???????????????
    if (this.options.remote) {
      this.$element
        .find('.modal-content')
        .load(this.options.remote, $.proxy(function () {
          this.$element.trigger('loaded.bs.modal')
        }, this))
    }
  }
  Modal.VERSION  = '3.3.7'

  Modal.TRANSITION_DURATION = 300
  Modal.BACKDROP_TRANSITION_DURATION = 150

  Modal.DEFAULTS = {
    backdrop: true, // 默认单击弹窗以外的地方时自动关闭弹窗
    keyboard: true, // 默认设置,按Esc键关闭弹窗
    show: true // 默认设置,单击触发元素时打开弹窗
  }

  Modal.prototype.toggle = function (_relatedTarget) {
    return this.isShown ? this.hide() : this.show(_relatedTarget)
  }
  Modal.prototype.show = function (_relatedTarget) {
    var that = this // Modal实例调用的show, 所以this指代Modal实例

    var e    = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
    this.$element.trigger(e)
    
    // ** 去执行 入口 中的 $target.one('show.bs.modal')

    if (this.isShown || e.isDefaultPrevented()) return
    this.isShown = true

    this.checkScrollbar()
    this.setScrollbar()
    this.$body.addClass('modal-open')

    this.escape()
    this.resize()

    // 触发关闭事件  // 点击 x
    this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))

    // ???????  或许是 当点击dialog时 不 移除弹框层???
    this.$dialog.on('mousedown.dismiss.bs.modal', function () {
      that.$element.one('mouseup.dismiss.bs.modal', function (e) {
        if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
      })
    })

    this.backdrop(function () {
      var transition = $.support.transition && that.$element.hasClass('fade')
      if (!that.$element.parent().length) {
        that.$element.appendTo(that.$body) // don't move modals dom position
      }

      that.$element
        .show()
        .scrollTop()

      that.adjustDialog()

      if (transition) {
        // ???????????
        that.$element[0].offsetWidth // force reflow
      }

      that.$element.addClass('in')

      that.enforceFocus() // 为什么要给弹出层加焦点 ????

      var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })

      // ??????????????
      transition ?
        that.$dialog // wait for modal to slide in
          .one('bsTransitionEnd', function () {
            that.$element.trigger('focus').trigger(e)
          })
          .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
        that.$element.trigger('focus').trigger(e)
    })

  }

  Modal.prototype.hide = function (e) {
    if (e) e.preventDefault()

    e = $.Event('hide.bs.modal')

    this.$element.trigger(e)

    if (!this.isShown || e.isDefaultPrevented()) return

    this.isShown = false

    this.escape()
    this.resize()

    $(document).off('focusin.bs.modal')

    this.$element
      .removeClass('in')
      .off('click.dismiss.bs.modal')
      .off('mouseup.dismiss.bs.modal')

    this.$dialog.off('mousedown.dismiss.bs.modal')


    
    $.support.transition && this.$element.hasClass('fade') ?
      this.$element
        .one('bsTransitionEnd', $.proxy(this.hideModal, this))
        .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
      this.hideModal()
  }

  // 强制给弹窗设定焦点
  Modal.prototype.enforceFocus = function () {
    $(document)
      .off('focusin.bs.modal') // guard against infinite focus loop
      .on('focusin.bs.modal', $.proxy(function (e) {
        if (document !== e.target &&
            this.$element[0] !== e.target &&
            !this.$element.has(e.target).length) {
          this.$element.trigger('focus')
          // ??????????? 设置焦点的作用
        }
      }, this))
  }

  Modal.prototype.escape = function () {
    if (this.isShown && this.options.keyboard) {
      this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
        e.which == 27 && this.hide()
      }, this))
    } else if (!this.isShown) {
      this.$element.off('keydown.dismiss.bs.modal')
    }
  }

  Modal.prototype.resize = function () {
    if (this.isShown) {
      $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
    } else {
      $(window).off('resize.bs.modal')
    }
  }

  Modal.prototype.hideModal = function () {
    // 把 id="myModal" 层隐藏
    
    var that = this
    this.$element.hide()

    // 调用原型上的  backdrop
    // 进入第二个条件 用来删除 半透明背景层

    this.backdrop(function () {
      that.$body.removeClass('modal-open')
      that.resetAdjustments()
      that.resetScrollbar()
      that.$element.trigger('hidden.bs.modal')
    })
  }

  Modal.prototype.removeBackdrop = function () {
    // 用来remove dom 节点 (手动添加的那个 dom节点)
    this.$backdrop && this.$backdrop.remove()
    this.$backdrop = null
  }

  Modal.prototype.backdrop = function (callback) {
    // 透明背景层 显示隐藏
    
    var that = this
    var animate = this.$element.hasClass('fade') ? 'fade' : ''
  // 是否支持css3动画  $.support.transition
    if (this.isShown && this.options.backdrop) {
      var doAnimate = $.support.transition && animate

      this.$backdrop = $(document.createElement('div'))
        .addClass('modal-backdrop ' + animate)
        .appendTo(this.$body)

        // 点击 模态框 关闭 dialog
      this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
        if (this.ignoreBackdropClick) {
          this.ignoreBackdropClick = false
          return
        }
        if (e.target !== e.currentTarget) return
        this.options.backdrop == 'static'
          ? this.$element[0].focus()
          : this.hide()
      }, this))

      if (doAnimate) this.$backdrop[0].offsetWidth // force reflow

      this.$backdrop.addClass('in')

      if (!callback) return

      doAnimate ?
        this.$backdrop
          .one('bsTransitionEnd', callback)
          .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
        callback()

    } else if (!this.isShown && this.$backdrop) {
      // 删除透明背景层(仅仅是删除控制的类名)
      this.$backdrop.removeClass('in')

      var callbackRemove = function () {
        that.removeBackdrop()
        callback && callback()
      }
      $.support.transition && this.$element.hasClass('fade') ?
        this.$backdrop
          .one('bsTransitionEnd', callbackRemove)
          .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
        callbackRemove()

    } else if (callback) {
      callback()
    }
  }

  // these following methods are used to handle overflowing modals

  Modal.prototype.handleUpdate = function () {
    this.adjustDialog()
  }

  Modal.prototype.adjustDialog = function () {
    // this.$element[0] js 对象
    var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight
    this.$element.css({
      paddingLeft:  !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
      paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
    })
  }

  Modal.prototype.resetAdjustments = function () {
    this.$element.css({
      paddingLeft: '',
      paddingRight: ''
    })
  }

  Modal.prototype.checkScrollbar = function () {
    var fullWindowWidth = window.innerWidth // 包含滚动条宽度
    if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
      var documentElementRect = document.documentElement.getBoundingClientRect()
      fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
    }
    this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
    // document.body.clientWidth  === fullWindowWidth
    // this.bodyIsOverflowing  -- > fasle
    this.scrollbarWidth = this.measureScrollbar()
  }

  Modal.prototype.setScrollbar = function () {
    var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
    this.originalBodyPad = document.body.style.paddingRight || ''
    if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
    // 等待
  }

  Modal.prototype.resetScrollbar = function () {
    this.$body.css('padding-right', this.originalBodyPad)
  }

  Modal.prototype.measureScrollbar = function () { // thx walsh
    // 创建一个div  获得滚动条的宽度
    var scrollDiv = document.createElement('div')
    scrollDiv.className = 'modal-scrollbar-measure'
    this.$body.append(scrollDiv)
    var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
    this.$body[0].removeChild(scrollDiv)
    return scrollbarWidth
  }


  // MODAL PLUGIN DEFINITION
  // =======================


  function Plugin(option, _relatedTarget) {

    /* **
      合并option
      判断data  data --> bs.modal
      如果不存在 则创建 Modal 实例

      如果 option ==== string
      否则

    * */
    // 参数 和 按钮
    return this.each(function () {
      var $this   = $(this) // 弹框层
      var data    = $this.data('bs.modal') // undefined
      var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)

      // if (!data) 和 if (typeof option == 'string')  每次只能执行一个
      // 如果 !data  创建 modal 实例
      if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
      // data --> Modal 的实例对象
      // $this.data() {bs.modal: Modal}
      // 执行modal 实例之后  执行以下代码

      // option 在再次点击按钮的时候 为string
      if (typeof option == 'string') data[option](_relatedTarget)
      else if (options.show) {
        data.show(_relatedTarget)
      } // 去执行 show 方法
      // data.show  dataw为 Modal实例
      // 所以 去执行show的prototype(把按钮传到show方法)
    })
  }


  // 防止冲突
  var old = $.fn.modal              // 保留(冲突中)老的那一个 这里是自定义的button插件
  $.fn.modal             = Plugin   // 使得 $("#btn1").button() 可以调用boot定义的button插件 这里是boot定义的button插件
  $.fn.modal.Constructor = Modal

  // MODAL NO CONFLICT
  // =================

  $.fn.modal.noConflict = function () {
    $.fn.modal = old // undefined = undefined
    return this
  }


  // MODAL DATA-API
  // ==============

  // $.fn.modal.noConflict()

  // 入口
  $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', 
  function (e) { // 点击buttons时

    /* 
    *  收集 option 对象或者 ‘toggle’ --> 根据是否存在 bs.modal判断

       执行show hide 事件

       执行 Plugin 函数
     */


    
    var $this   = $(this) // jquery 实例对象 ——> 按钮

    var href    = $this.attr('href') // 得到 href属性值

    // 弹出框
    // ??????? 仍然不知道这个正则是干什么的啊
    var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7

    // 目标弹出框  button按钮上的data-target属性 或者是 存在href 并且 href  remote ?????
    var option  = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
  // option  如果弹出框缓存了 data-bs.modal 那么 option 是 toggle  否则  $.extend(), 这个扩展方法 是 把 参数 2 3 和 参数1合并;

    // 如果是a标签,则阻止a标签的默认行为
    if ($this.is('a')) e.preventDefault()



    // 先执行call 再执行show prototype  最后执行 one
    $target.one('show.bs.modal', function (showEvent) {
      if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
      $target.one('hidden.bs.modal', function () {
        $this.is(':visible') && $this.trigger('focus')
      })
    })

    // arguments1  $target  把plugin 中的this 指向 $target(弹框),
    // option, this  仅仅是参数
    Plugin.call($target, option, this)
  })

}(jQuery);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章