bootstrap modal彈出框的垂直居中

本人前端小菜雞一隻,公司項目嘗試採用bootstrap,我身先士卒爲同事趟“坑”,無奈UI妹子刁難非得讓modal彈出框垂直居中,爲了前端開發崗位的榮譽,花時間滿足之。
最先就是百度咯,方法,就是修改源碼

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

這裏的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時間忽閃忽閃的過於誇張跟原來的還是有點異樣,求過路大神,提點

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章