Bootstrap modal 模态框垂直居中

2017 年 2 月 4 日 0 条评论 1.84k 次阅读 0 人点赞

最近在使用Bootstrap框架,框架本身自带有一个modal模态框,也就是我们平时常叫的弹窗。但是这个模态框有一个特点,就是它本身是不会垂直居中的,默认只是距离顶部30px。那有没有办法让模态框垂直居中呢?有!
一个思路就是使用table布局,table布局的元素默认就是垂直居中的,在把外层.modal 元素设置为display: table ,里层.modal-dialog 元素设置为display: table-cell 之后却发现点击背后半透明的黑色遮罩无法使模态框消失了。所以table 方案 out!
另一个思路则是使用动态计算的方式,先贴上代码:

/**
* 使页面中所有.modal元素在窗口可视范围之内居中
**/
function centerModals(){
 $('.modal').each(function(i){
 var $clone = $(this).clone().css('display', 'block').appendTo('body');
 var top = Math.round(($clone.height() - $clone.find('.modal-content').height()) / 2);
 top = top > 50 ? top : 0;
 $clone.remove();
 $(this).find('.modal-content').css("margin-top", top-50);
 });
}
// 在模态框出现的时候调用垂直居中函数
$('.modal').on('show.bs.modal', centerModals);
// 在窗口大小改变的时候调用垂直居中函数
$(window).on('resize', centerModals);

下面来进行解释,仔细观察会发现,centerModals 函数中在top判断时有一个50的高度,因为人的视觉在观察居中时,会有一点点偏差,这个数值可以根据个人的喜好去调整。

雷雷

这个人太懒什么东西都没留下

文章评论(0)

(Spamcheck Enabled)