讀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);

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