首頁  >  文章  >  web前端  >  如何修復 Bootstrap 中的重疊模態:使用 setTimeout 和 Z-Index 管理的簡單解。

如何修復 Bootstrap 中的重疊模態:使用 setTimeout 和 Z-Index 管理的簡單解。

Barbara Streisand
Barbara Streisand原創
2024-10-26 02:14:02383瀏覽

How to Fix Overlapping Modals in Bootstrap:  A Simple Solution with setTimeout and Z-Index Management.

多個模態輕鬆疊加

遇到多個模態相互疊加可能會令人沮喪,尤其是當您需要新模態出現在頂部時位於現有的後面。為了解決這個問題,我們將深入研究一個受兩位傑出貢獻者啟發的解決方案:@YermoLamers 和 @Ketwaroo。

Backdrop Z-Index Fix

此解決方案依賴於在 setTimeout 函數上,因為觸發 show.bs.modal 事件時尚未創建 .modal-backdrop 元素。

<code class="javascript">$(document).on('show.bs.modal', '.modal', function() {
  const zIndex = 1040 + 10 * $('.modal:visible').length;
  $(this).css('z-index', zIndex);
  setTimeout(() => $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack'));
});</code>

這個方法有幾個優點:

  • 它適用於頁面上的所有 .modal 元素,包括動態建立的元素。
  • 背景立即覆蓋之前的模態。

Z-Index 計算

如果不想硬編碼z-index,可以動態計算頁面上的最高z-index:

<code class="javascript">const zIndex = 10 +
  Math.max(...Array.from(document.querySelectorAll('*')).map((el) => +el.style.zIndex));</code>

捲軸修復

如果模態框超出瀏覽器高度,則關閉內部模態框時可能會遇到捲動問題。要解決此問題,請添加以下內容:

<code class="javascript">$(document).on('hidden.bs.modal', '.modal',
  () => $('.modal:visible').length && $(document.body).addClass('modal-open'));</code>

相容性

此解決方案已使用Bootstrap 版本3.1.0 - 3.3.5 進行了測試。

JSFiddle 範例

[JSFiddle 範例](https://jsfiddle.net/)

以上是如何修復 Bootstrap 中的重疊模態:使用 setTimeout 和 Z-Index 管理的簡單解。的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn