用一個之前建置的頁面來套版改寫,其中有用到 Bootstrap 3 的內置視窗 (modal) 功能,在舊網站裡連續開兩個也能正常顯示,但是在改寫後的另一個子網站裡使用,不知道被頁面上什麼內容干擾了,原本在 modal 跳出後底部遮蔽內容用的灰色遮罩,會在某一層 modal 出現後,就蓋在整個畫面上,連 modal 都被蓋住了。
這個情況是 body 裡的 class "modal-open" 不知道在什麼狀況下被移除了,補回去就好了。
原本是在各個段落裡確認 modal 出現異常的遮罩時補上,但是如果不加個半秒的遞延,又會被蓋過去,我猜是 modal 的動畫影響的?
$('#thisModal').on('hidden.bs.modal', function (e) {
setTimeout(function () {
// 在 "thisModal" 這個 modal 關閉時,在 body 裡加上 class "modal-open"
$("body").addClass("modal-open");
}, 200);
});
後來看到 "Closing modal removes modal-open class from body even if it shouldn't" 教學,說可以加一段這樣的 JavaScript:
(function($) {
$(document).on('hidden.bs.modal', function () { if($('.modal.fade').length) { $('body').removeClass('modal-open'); } });
$(document).on('hidden.bs.modal', function () { if($('.modal.in').length) { $('body').addClass('modal-open'); } });
}(jQuery));
原理是先檢查看看有沒有正在啟動的 modal,有就先把 body 裡加上 modal-open 的 class,如果反過來,就移除掉。不過如果只加這個,在多開幾次 modal 後仍然會發生問題,所以我調整成除了在關閉 modal 時 (hidden.bs.modal) 檢查是否要增減 modal-open,在開啟 modal 時 (shown.bs.modal) 也加上去:
(function($) {
$(document).on('hidden.bs.modal', function () { if($('.modal.fade').length) { $('body').removeClass('modal-open'); } });
$(document).on('hidden.bs.modal', function () { if($('.modal.in').length) { $('body').addClass('modal-open'); } });
$(document).on('shown.bs.modal', function () { if($('.modal.fade').length) { $('body').removeClass('modal-open'); } });
$(document).on('shown.bs.modal', function () { if($('.modal.in').length) { $('body').addClass('modal-open'); } });
}(jQuery));
我嘗試在頁面載入時就執行好關閉 modal 與開啟 modal 時檢視是否要增加 modal-open 的檢查,就沒事了。
也有其他解法,像《bootstrap modal 關閉後還有灰色背景無法操作頁面問題解決》的解決辦法是,拿掉 HTML 裡的 modal 啟動屬性:
data-toggle="modal" data-target="{ID}",
直接利用 JavaScript 驅動 modal:
$("{ID}").modal("show");
不過我檢查了一下,我也沒有加那些 HTML 屬性。實際上用 JavaScript 重新啟動一次 modal 顯示,的確可以幫助 body 加入 modal-open 這個樣式。