bootstrap modal垂直居中 (转)

 根据博友的经验,总结后请使用方法一就行了

一,修改bootstrap.js 源码

原来的:

  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.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 : ''
    })
    //弹出框居中
    var $modal_dialog = $(this.$element[0]).find('.modal-dialog');
    var m_top = ( $(window).height() - $modal_dialog.height() )/2;//浏览器高 - 模态框高 再 / 2
    $modal_dialog.css({'margin': m_top + 'px auto'});
  }

如果垂直居中了

 

二,jquery中

<script type="text/javascript">
      $(function(){
        // dom加载完毕
        var $m_btn = $('#modalBtn');
        var $modal = $('#myModal');
        $m_btn.on('click', function(){
          $modal.modal({backdrop: 'static'});
        });

        // 测试 bootstrap 居中
        $modal.on('show.bs.modal', function(){
          var $this = $(this);
          var $modal_dialog = $this.find('.modal-dialog');
          // 关键代码,如没将modal设置为 block,则$modala_dialog.height() 为零
          $this.css('display', 'block');
          $modal_dialog.css({'margin-top': Math.max(0, ($(window).height() - $modal_dialog.height()) / 2) });
        });
        
      });
    </script>

 这里参考这位博友吧:http://www.cnblogs.com/zzj-suxiao/articles/5460972.html

 

posted @ 2017-02-20 15:23  James2019  阅读(238)  评论(0编辑  收藏  举报