bootstrap modal彈出框的垂直居中
本人前端菜鳥,公司項目嘗試采用bootstrap,我身先士卒為同事趟“坑”,無奈UI妹子刁難非得讓modal彈出框垂直居中,為了前端開發(fā)崗位的榮譽,花時間滿足之。
最先就是百度咯,方法,就是修改源碼
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,也就是它還沒創(chuàng)建,獲取不到值,菜鳥拙見,加了個setTimeout 150ms的延遲,倒是獲取到了,妥妥的居中,又蹦出兩個問題,一個是用戶主動拖動窗口大小的時候,它不會跟著自適應(yīng),解決方法也很簡單寫個resize方法;第二個問題是當窗口小于時600時that.element.children().eq(0).width()的值時而對,時而不對(求大神路過幫忙解答),故棄之
想直接解決問題看上邊直接忽略
垂直居中考慮到display:table-cell,也受網(wǎng)上的啟發(fā),解決方法如下。
重寫樣式并style標簽或外聯(lián)引入html內(nèi)
.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觸發(fā)事件$(‘.modal').modal()改為如下
$('.modal').modal().css({'display':'table','width':'100%','height':'100%'})
改起來很簡單,也很暴力,后果就是在任意處點擊讓modal消失的事件失效了,我搜的資料如是說我搜的資料,但我沒看懂咋整

雖然點擊叉子和close按鈕都可以實現(xiàn)關(guān)閉,但是不能讓后臺同事看不起啊,自己想了想在js里插入兩行醬紫的代碼
$(觸發(fā)器).click(function(){
$('.modal').modal().css({'display':'table','width':'100%','height':'100%'})//這句觸發(fā)modal
$('.modal-backdrop').fadeIn()
event.stopPropagation();//因為觸發(fā)的元素肯定在document里邊,所以必須阻止冒泡
})
$(document).click(function(){
$('.modal').hide()
$('.modal-backdrop').fadeOut()
})
到此,能實現(xiàn)modal的垂直居中,但問題還是有的,modal-backdrop的fadein時間和fadeout時間忽閃忽閃的過于夸張跟原來的還是有點異樣,求過路大神,提點。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Javascript中查找不以XX字符結(jié)尾的單詞示例代碼
我在寫這篇文章之前花了2個多小時在弄正則表達式,下為大家介紹下具體的實現(xiàn)思路,感興趣的朋友可以參考下2013-10-10
基于slideout.js實現(xiàn)移動端側(cè)邊欄滑動特效
這篇文章主要為大家詳細介紹了基于slideout.js實現(xiàn)移動端側(cè)邊欄滑動特效,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-11-11

