bootstrap彈出模態框「bootstrap模態框關閉事件」

當點擊按鈕時modal的位置看起來很不舒服, 解決辦法總結有兩:

1.使用modal 彈出事件方法;

從官方文檔中可以了解到, modal組件有不少事件接口:

BootStrap3.X模態框垂直居中顯示

其中 「shown.bs.modal」可以在彈窗框出現後 做一些處理, 更改彈出框的樣式當然是可以的:

<script type=”text/javascript”>

$(function(){

// dom加載完畢

var $m_btn = $(『#modalBtn『);

var $modal = $(『#myModal『);

$m_btn.on(『click『, function(){

$modal.modal({backdrop: 『static『});

});

// 測試 bootstrap 居中

$modal.on(『shown.bs.modal『, function(){

var $this = $(this);

var $modal_dialog = $this.find(『.modal-dialog『);

var m_top = ( $(document).height() – $modal_dialog.height() )/2; $modal_dialog.css({『margin『: m_top + 『px auto『});

});

});

</script>

該實現方式 彈出框是居中了, 但彈出時有一些遲疑後抖動到中部;不是特別理想, 接下來試試第二種方式;

2.修改bootstrap.js 源碼;

帶着問題讀js庫源碼, 往往能學到不少知識;本着怎樣讓 modal組件自動居中目的, 開始跟蹤組件彈窗時對應的事件;

打開bootstrap.js ctrl+f 找到 modal對應代碼:

BootStrap3.X模態框垂直居中顯示

彈出框出現時, 調用的自然是 Modal.prototype.show() 方法, 而show 方法中又調用了 that.adjustDialog() 方法:

BootStrap3.X模態框垂直居中顯示

以上代碼看來,官方要實現 垂直居中簡直太容易, 而他們沒有, 只能說國外同行網站布局觀跟俺們還是有區別的。加上少量代碼:

Modal.prototype.adjustDialog = function () {

var modalIsOverflowing=this.$element[0].scrollHeight> document.documentElement.clientHeight

this.$element.css({

paddingLeft:!this.bodyIsOverflowing&&modalIsOverflowing?this.scrollbarWidth:”,

paddingRight: this.bodyIsOverflowing &&!modalIsOverflowing?this.scrollbarWidth:”

})

// 是彈出框居中…

var $modal_dialog = $(this.$element[0]).find(‘ .modal-dialog’ );

var m_top = ( $(document).height() – $modal_dialog.height() )/2; $modal_dialog.css({‘margin’ : m_top + ‘px auto’});

}

然後就實現modal垂直居中了, 效果圖:

BootStrap3.X模態框垂直居中顯示

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/252299.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-14 02:15
下一篇 2024-12-14 02:15

相關推薦

發表回復

登錄後才能評論