bootstrap modal弹出框的垂直居中

本人前端菜鸟,公司项目尝试采用bootstrap,我身先士卒为同事趟“坑”,无奈UI妹子刁难非得让modal弹出框垂直居中,为了前端开发岗位的荣誉,花时间满足之。

最先就是百度咯,方法,就是修改源码

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";

}

});

这里的that.element就是最外层的div.modal ,that.element.children().eq(0)就是div.modal-dialog,无非就是计算里边modal-dialog的left值和height值来让它居中咯,问题来了,你把这段代码加入bootstrap.js的源码(大概1000行左右的样子),可以console到that.element.children().eq(0).width()一直为0,也就是它还没创建,获取不到值,菜鸟拙见,加了个setTimeout 150ms的延迟,倒是获取到了,妥妥的居中,又蹦出两个问题,一个是用户主动拖动窗口大小的时候,它不会跟着自适应,解决方法也很简单写个resize方法;第二个问题是当窗口小于时600时that.element.children().eq(0).width()的值时而对,时而不对(求大神路过帮忙解答),故弃之

想直接解决问题看上边直接忽略

垂直居中考虑到display:table-cell,也受网上的启发,解决方法如下。

重写样式并style标签或外联引入html内

.modal-dialog{display:table-cell;vertical-align:middle;}

.modal-content{width:600px;margin:0px auto;}

@media screen and (max-width: 780px) {

.modal-content{width:400px;}

}

@media screen and (max-width: 550px) {

.modal-content{width:220px;}

}

将modal触发事件$(‘.modal').modal()改为如下

$('.modal').modal().css({'display':'table','width':'100%','height':'100%'})

改起来很简单,也很暴力,后果就是在任意处点击让modal消失的事件失效了,我搜的资料如是说我搜的资料,但我没看懂咋整

虽然点击叉子和close按钮都可以实现关闭,但是不能让后台同事看不起啊,自己想了想在js里插入两行酱紫的代码

$(触发器).click(function(){

$('.modal').modal().css({'display':'table','width':'100%','height':'100%'})//这句触发modal

$('.modal-backdrop').fadeIn()

event.stopPropagation();//因为触发的元素肯定在document里边,所以必须阻止冒泡

})

$(document).click(function(){

$('.modal').hide()

$('.modal-backdrop').fadeOut()

})

到此,能实现modal的垂直居中,但问题还是有的,modal-backdrop的fadein时间和fadeout时间忽闪忽闪的过于夸张跟原来的还是有点异样,求过路大神,提点。

以上是 bootstrap modal弹出框的垂直居中 的全部内容, 来源链接: utcz.com/z/337258.html

回到顶部