首页 > Web开发 > 详细

Bootstrap源码:modal.js

时间:2015-08-19 23:49:24      阅读:543      评论:0      收藏:0      [点我收藏+]

modal.js对应的是bs的模态框组件。该组件主要有以下特点:

  1. 并不是绝对居中于浏览器窗口,而是水平居中,同时顶部距离浏览器顶部有一定的距离,其原因是因为modal框的内容可能出现滚动,垂直居中不太可能,它没有做成模态框内部滚动的效果;

  2. 动画是通过css3的translate实现的:transform: translate(0, -25%);

  3. 遮罩层的元素不是包含在modal里面的,而是与modal元素平级,都是body元素的子元素

  4. 不支持在已弹出的modal上继续弹框,主要是遮罩层叠加的问题

  5. 该组件内部包含一些如网页宽度计算,浏览器滚动条计算的函数,有一些学习的价值

  6. 事件监听这一块写的不太合理,混杂在各个具体的方法中,而不是统一地在一处管理

以下是具体代码,解释都以注释的形式说明,bs官方给出的例子中包含的html和css,再多看几遍注释,应该能很好地理解该组件的实现:

/* ========================================================================
 * Bootstrap: modal.js v3.3.4
 * http://getbootstrap.com/javascript/#modals
 * ========================================================================
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */
+function ($) {
  ‘use strict‘;
  // MODAL CLASS DEFINITION
  // ======================
  var Modal = function (element, options) {
    this.options             = options
    this.$body               = $(document.body)
    this.$element            = $(element) //.modal对应的元素
    this.$dialog             = this.$element.find(‘.modal-dialog‘) 
    this.$backdrop           = null //遮罩元素,如果没有这个元素,在IE9下,被模态窗口覆盖的链接、按钮仍能继续点击
    this.isShown             = null
    this.originalBodyPad     = null //保留body元素原来的padding值
    this.scrollbarWidth      = 0
    this.ignoreBackdropClick = false //是否忽略遮罩元素上的点击,默认的情况是点击遮罩会隐藏modal元素
    //异步加载模态窗口的内容,如果通过remote配置了异步加载地址的话
    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.4‘
  Modal.TRANSITION_DURATION = 300
  Modal.BACKDROP_TRANSITION_DURATION = 150 
  Modal.DEFAULTS = {
    backdrop: true,//是否需要遮罩
    keyboard: true,//是否支持按esc键时隐藏模态窗口
    show: true//是否在$(..).modal()的时候立即弹出模态窗口
  }
  Modal.prototype.toggle = function (_relatedTarget) {
    return this.isShown ? this.hide() : this.show(_relatedTarget)
  }
  Modal.prototype.show = function (_relatedTarget) {
    var that = this
    var e    = $.Event(‘show.bs.modal‘, { relatedTarget: _relatedTarget })
    this.$element.trigger(e)
    if (this.isShown || e.isDefaultPrevented()) return
    this.isShown = true
    this.checkScrollbar()
    this.setScrollbar()
    this.$body.addClass(‘modal-open‘)//设置overflow:hidden,在body元素溢出时隐藏body元素的滚动条
    this.escape()
    this.resize()
    //模态框的关闭按钮
    this.$element.on(‘click.dismiss.bs.modal‘, ‘[data-dismiss="modal"]‘, $.proxy(this.hide, this))
    //点击dialog的时候不会触发hide
    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
      })
    })
    //先处理遮罩元素,再调用回调显示modal元素
    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(0)//有可能有溢出,每次弹出的时候都滚到最顶部
      that.adjustDialog()
      if (transition) {
        that.$element[0].offsetWidth // force reflow
      }
      //force reflow 跟浏览器渲染有关,虽然这样会有损性能,但是如果不这么调用的话,有可能z-index的渲染会有问题,
      //因为浏览器对dom处理的缓存机制
      //触发动画
      that.$element
        .addClass(‘in‘)
        .attr(‘aria-hidden‘, false)
      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
  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‘)
    //开始进行关闭动画,移除show的时候绑定的事件监听器
    this.$element
      .removeClass(‘in‘)
      .attr(‘aria-hidden‘, true)
      .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()
  }
  //focusin事件支持代理,focus事件不支持,enforceFocus方法的目的是
  //当document捕获到focusin事件时,说明内部有元素获得了焦点
  //假如这个焦点元素不在modal元素内,那么强制触发modal元素focus事件,使其获得焦点
  Modal.prototype.enforceFocus = function () {
    $(document)
      .off(‘focusin.bs.modal‘) // guard against infinite focus loop
      .on(‘focusin.bs.modal‘, $.proxy(function (e) {
        if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
          this.$element.trigger(‘focus‘)
        }
      }, this))
  }
  //ESC键的处理,show与hide方法都会调用
  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‘)
    }
  }
  //widnow resize的处理
  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 () {
    var that = this
    this.$element.hide()
    this.backdrop(function () {
      that.$body.removeClass(‘modal-open‘)//恢复溢出
      that.resetAdjustments()//取消modal元素的左右padding
      that.resetScrollbar()//重置body元素的padding-right
      that.$element.trigger(‘hidden.bs.modal‘)
    })
  }
  //删除遮罩元素
  Modal.prototype.removeBackdrop = function () {
    this.$backdrop && this.$backdrop.remove()
    this.$backdrop = null
  }
  //遮罩处理
  Modal.prototype.backdrop = function (callback) {
    var that = this
    var animate = this.$element.hasClass(‘fade‘) ? ‘fade‘ : ‘‘
    if (this.isShown && this.options.backdrop) {
      var doAnimate = $.support.transition && animate
      this.$backdrop = $(‘<div class="modal-backdrop ‘ + animate + ‘" />‘)
        .appendTo(this.$body)
      this.$element.on(‘click.dismiss.bs.modal‘, $.proxy(function (e) {
        //如果点的是dialog就返回
        if (this.ignoreBackdropClick) {
          this.ignoreBackdropClick = false
          return
        }
            
        if (e.target !== e.currentTarget) return
        //如果options.backdrop配置不是static,那么点的空白部分时就会隐藏modal
        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()
  }
  //在show的时候,以及浏览器窗口调整的时候调用,目的是:
  //在body溢出而modal没有溢出的时候,给modal添加padding-right
  //在body没有溢出而modal溢出的时候,给modal添加padding-left
  //目的还是为了让modal元素水平居中于浏览器窗口中
  Modal.prototype.adjustDialog = function () {
    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元素的左右padding,这主要是因为adjustDialog方法的调用,所以在hide的时候得还原
  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//记录body元素是否有溢出
    this.scrollbarWidth = this.measureScrollbar()//得到当前浏览器滚动条的宽度
  }
  //在body发生溢出的时候,给body添加padding-right。该值等于当前浏览器滚动条的宽度加上body元素原有的padding-right
  //这个是在show方法调用的时候才会调的,目的是为了让modal元素完全水平居中在浏览器窗口中
  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)
  }
  //在hide的时候重置body元素的padding-right
  Modal.prototype.resetScrollbar = function () {
    this.$body.css(‘padding-right‘, this.originalBodyPad)
  }
  //计算当前浏览器的滚动条宽度
  Modal.prototype.measureScrollbar = function () { // thx walsh
    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) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data(‘bs.modal‘)
      var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == ‘object‘ && option)
      if (!data) $this.data(‘bs.modal‘, (data = new Modal(this, options)))
      if (typeof option == ‘string‘) data[option](_relatedTarget)
      else if (options.show) data.show(_relatedTarget)
    })
  }
  var old = $.fn.modal
  $.fn.modal             = Plugin
  $.fn.modal.Constructor = Modal
  // MODAL NO CONFLICT
  // =================
  $.fn.modal.noConflict = function () {
    $.fn.modal = old
    return this
  }
  // MODAL DATA-API
  // ==============
  $(document).on(‘click.bs.modal.data-api‘, ‘[data-toggle="modal"]‘, function (e) {
    var $this   = $(this)
    var href    = $this.attr(‘href‘)
    var $target = $($this.attr(‘data-target‘) || (href && href.replace(/.*(?=#[^\s]+$)/, ‘‘))) // strip for ie7
    var option  = $target.data(‘bs.modal‘) ? ‘toggle‘ : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
    if ($this.is(‘a‘)) e.preventDefault()
    $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‘)
      })
    })
    Plugin.call($target, option, this)
  })
}(jQuery);

Bootstrap源码:modal.js

原文:http://my.oschina.net/lyzg/blog/494815

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!