Bootstrap 弹出框modal 垂直居中(适用各种分辨率窗口)

用的是bootstrap3.X的版本,在网上找了各种方法,

有的说在modal中加css top=($(window).height()-$(this).height())/2

这个方法确实可以,但是是建立在大分辨率的前提下,不能有垂直滚动条。否则弹出框位置会不确定。

还有人说加下面这段代码可以完美解决滚动条问题,简直扯淡。

var left = ($(document.body).width() - that.$element.width()) / 2; 
var top = ($(document.body).height() - that.$element.height()) / 2;
var scrollY = document.documentElement.scrollTop || document.body.scrollTop; //滚动条解决办法
var top = (window.screen.height / 4) + scrollY - 120; //滚动条解决办法
console.log(left); 
that.$element 
.addClass('in') 
.attr('aria-hidden', false) 
.css({ 
left: left, 
top: top, 
margin: "0 auto" 
});
that.enforceFocus()

最后终于找到完美解决办法:

在bootstrap.js或bootstrap.min.js文件中找到Modal.prototype.show方法。

在that.$element.addClass('in').attr('aria-hidden', false)代码前加入下面这段代码。

that.$element.children().eq(0).css("position", "absolute").css({
          "margin": "0px",
          "top": function () {
              return (that.$element.height() - that.$element.children().eq(0).height() - 40) / 2 + "px";
          },
          "left": function () {
              return (that.$element.width() - that.$element.children().eq(0).width()) / 2 + "px";
          }
      });





亲测有效,特此记录。而且此方法也能解决bootbox无法居中的问题。


原文地址:https://www.cnblogs.com/neso520/p/12491258.html