跳到主要內容 跳到文件導覽

使用 Bootstrap 的 JavaScript 模態對話框外掛程式,為您的網站加入對話框,以用於燈箱、使用者通知或完全自訂的內容。

運作方式

在開始使用 Bootstrap 的模態對話框元件之前,請務必閱讀以下內容,因為我們的選單選項最近已變更。

  • 模態對話框使用 HTML、CSS 和 JavaScript 建置。它們會置於文件中的所有其他內容之上,並從 <body> 中移除捲動,以便模態對話框內容改為捲動。
  • 按一下對話框「背景」會自動關閉對話框。
  • Bootstrap 一次只支援一個對話框視窗。我們認為巢狀對話框會造成不佳的使用者體驗,因此不支援。
  • 對話框使用 position: fixed,有時可能會對其呈現有點特別。只要有可能,請將對話框 HTML 放置在頂層位置,以避免其他元素造成潛在的干擾。將 .modal 巢狀嵌在另一個固定元素中時,可能會遇到問題。
  • 由於 position: fixed,在行動裝置上使用對話框時,會有一些注意事項。請參閱我們的 瀏覽器支援文件 以取得詳細資訊。
  • 由於 HTML5 定義其語意,autofocus HTML 屬性 在 Bootstrap 對話框中沒有作用。若要達到相同的目的,請使用一些自訂 JavaScript
const myModal = document.getElementById('myModal')
const myInput = document.getElementById('myInput')

myModal.addEventListener('shown.bs.modal', () => {
  myInput.focus()
})
此元件的動畫效果會依賴 prefers-reduced-motion 媒體查詢。請參閱我們無障礙文件中的 減少動作部分

請繼續閱讀以取得示範和使用指南。

範例

以下是靜態對話框範例(表示其 positiondisplay 已被覆寫)。其中包含對話框標頭、對話框主體(需要 padding)和對話框頁尾(選用)。我們要求您盡可能使用具有關閉動作的對話框標頭,或提供其他明確的關閉動作。

<div class="modal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p>Modal body text goes here.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
在上述靜態範例中,我們使用 <h5>,以避免文件頁面中標題層級的問題。然而,在結構上,模態對話框代表其自己的獨立文件/內容,因此 .modal-title 理想上應為 <h1>。如有必要,您可以使用 字體大小工具程式 來控制標題的外觀。以下所有實際範例都使用此方法。

實際範例

按一下下方按鈕,切換一個可用的模態對話框範例。它將從頁面頂端向下滑動並淡入。

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

靜態背景

當背景設定為靜態時,按一下模態對話框外部時,模態對話框不會關閉。按一下下方按鈕試試看。

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
  Launch static backdrop modal
</button>

<!-- Modal -->
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="staticBackdropLabel">Modal title</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Understood</button>
      </div>
    </div>
  </div>
</div>

捲動長內容

當模態對話框變得比使用者的視窗或裝置還長時,它們會獨立於頁面本身捲動。試試看下方範例,了解我們的用意。

您也可以建立一個可捲動模態對話框,讓您可以透過將 .modal-dialog-scrollable 加入 .modal-dialog 來捲動模態對話框主體。

<!-- Scrollable modal -->
<div class="modal-dialog modal-dialog-scrollable">
  ...
</div>

垂直置中

.modal-dialog-centered 加入 .modal-dialog 以垂直置中對話框。

<!-- Vertically centered modal -->
<div class="modal-dialog modal-dialog-centered">
  ...
</div>

<!-- Vertically centered scrollable modal -->
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
  ...
</div>

工具提示和彈出框

工具提示彈出框 可視需要置於對話框內。當對話框關閉時,對話框內的任何工具提示和彈出框也會自動關閉。

<div class="modal-body">
  <h2 class="fs-5">Popover in a modal</h2>
  <p>This <button class="btn btn-secondary" data-bs-toggle="popover" title="Popover title" data-bs-content="Popover body content is set in this attribute.">button</button> triggers a popover on click.</p>
  <hr>
  <h2 class="fs-5">Tooltips in a modal</h2>
  <p><a href="#" data-bs-toggle="tooltip" title="Tooltip">This link</a> and <a href="#" data-bs-toggle="tooltip" title="Tooltip">that link</a> have tooltips on hover.</p>
</div>

使用網格

透過在 .modal-body 內嵌套 .container-fluid,在對話框內使用 Bootstrap 網格系統。然後,像在其他地方一樣使用正常的網格系統類別。

<div class="modal-body">
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-4">.col-md-4</div>
      <div class="col-md-4 ms-auto">.col-md-4 .ms-auto</div>
    </div>
    <div class="row">
      <div class="col-md-3 ms-auto">.col-md-3 .ms-auto</div>
      <div class="col-md-2 ms-auto">.col-md-2 .ms-auto</div>
    </div>
    <div class="row">
      <div class="col-md-6 ms-auto">.col-md-6 .ms-auto</div>
    </div>
    <div class="row">
      <div class="col-sm-9">
        Level 1: .col-sm-9
        <div class="row">
          <div class="col-8 col-sm-6">
            Level 2: .col-8 .col-sm-6
          </div>
          <div class="col-4 col-sm-6">
            Level 2: .col-4 .col-sm-6
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

變更模態視窗內容

有許多按鈕,全部會觸發內容略有不同的同一個模態視窗嗎?請使用 event.relatedTargetHTML data-bs-* 屬性,根據按下的按鈕來變更模態視窗的內容。

以下是動態示範,後面接著範例 HTML 和 JavaScript。如需更多資訊,請閱讀模態視窗事件文件,以取得 relatedTarget 的詳細資料。

html
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" data-bs-whatever="@mdo">Open modal for @mdo</button>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" data-bs-whatever="@fat">Open modal for @fat</button>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" data-bs-whatever="@getbootstrap">Open modal for @getbootstrap</button>

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="exampleModalLabel">New message</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form>
          <div class="mb-3">
            <label for="recipient-name" class="col-form-label">Recipient:</label>
            <input type="text" class="form-control" id="recipient-name">
          </div>
          <div class="mb-3">
            <label for="message-text" class="col-form-label">Message:</label>
            <textarea class="form-control" id="message-text"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Send message</button>
      </div>
    </div>
  </div>
</div>
const exampleModal = document.getElementById('exampleModal')
if (exampleModal) {
  exampleModal.addEventListener('show.bs.modal', event => {
    // Button that triggered the modal
    const button = event.relatedTarget
    // Extract info from data-bs-* attributes
    const recipient = button.getAttribute('data-bs-whatever')
    // If necessary, you could initiate an Ajax request here
    // and then do the updating in a callback.

    // Update the modal's content.
    const modalTitle = exampleModal.querySelector('.modal-title')
    const modalBodyInput = exampleModal.querySelector('.modal-body input')

    modalTitle.textContent = `New message to ${recipient}`
    modalBodyInput.value = recipient
  })
}

在模態視窗之間切換

透過巧妙地配置 data-bs-targetdata-bs-toggle 屬性,在多個模態視窗之間切換。例如,您可以在已開啟的登入模態視窗中切換密碼重設模態視窗。請注意,無法同時開啟多個模態視窗,此方法僅在兩個獨立的模態視窗之間切換。

html
<div class="modal fade" id="exampleModalToggle" aria-hidden="true" aria-labelledby="exampleModalToggleLabel" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="exampleModalToggleLabel">Modal 1</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        Show a second modal and hide this one with the button below.
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" data-bs-target="#exampleModalToggle2" data-bs-toggle="modal">Open second modal</button>
      </div>
    </div>
  </div>
</div>
<div class="modal fade" id="exampleModalToggle2" aria-hidden="true" aria-labelledby="exampleModalToggleLabel2" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="exampleModalToggleLabel2">Modal 2</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        Hide this modal and show the first with the button below.
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" data-bs-target="#exampleModalToggle" data-bs-toggle="modal">Back to first</button>
      </div>
    </div>
  </div>
</div>
<button class="btn btn-primary" data-bs-target="#exampleModalToggle" data-bs-toggle="modal">Open first modal</button>

變更動畫

$modal-fade-transform 變數決定在 modal 淡入動畫之前 .modal-dialog 的變形狀態,$modal-show-transform 變數決定在 modal 淡入動畫結束時 .modal-dialog 的變形。

例如,如果您想要縮放動畫,您可以設定 $modal-fade-transform: scale(.8)

移除動畫

對於直接出現而不是淡入顯示的 modal,請從您的 modal 標記中移除 .fade 類別。

<div class="modal" tabindex="-1" aria-labelledby="..." aria-hidden="true">
  ...
</div>

動態高度

如果 modal 的高度在開啟時改變,您應該呼叫 myModal.handleUpdate() 來重新調整 modal 的位置,以防出現捲軸。

無障礙

務必將 aria-labelledby="..."(參照 modal 標題)新增到 .modal。此外,您可以在 .modal 上使用 aria-describedby 來提供 modal 對話框的說明。請注意,您不需要新增 role="dialog",因為我們已經透過 JavaScript 新增了。

嵌入 YouTube 影片

在 modal 中嵌入 YouTube 影片需要額外的 JavaScript(不在 Bootstrap 中),才能自動停止播放等功能。請參閱此有用的 Stack Overflow 文章以取得更多資訊。

選用大小

Modal 有三種選用大小,可透過置於 .modal-dialog 上的修改器類別取得。這些大小會在特定中斷點啟動,以避免在較窄的視窗中出現水平捲軸。

大小 類別 Modal 最大寬度
.modal-sm 300px
預設 500px
.modal-lg 800px
特大 .modal-xl 1140px

我們的預設 modal 沒有修改器類別,構成「中」大小的 modal。

<div class="modal-dialog modal-xl">...</div>
<div class="modal-dialog modal-lg">...</div>
<div class="modal-dialog modal-sm">...</div>

全螢幕 Modal

另一個覆寫是選項,可以彈出一個涵蓋使用者視窗的 modal,可透過放置在 .modal-dialog 上的修改器類別使用。

類別 可用性
.modal-fullscreen 總是
.modal-fullscreen-sm-down 576px
.modal-fullscreen-md-down 768px
.modal-fullscreen-lg-down 992px
.modal-fullscreen-xl-down 1200px
.modal-fullscreen-xxl-down 1400px
<!-- Full screen modal -->
<div class="modal-dialog modal-fullscreen-sm-down">
  ...
</div>

CSS

變數

在 v5.2.0 中新增

作為 Bootstrap 不斷演進的 CSS 變數方法的一部份,modal 現在使用 .modal.modal-backdrop 上的本機 CSS 變數,以增強即時自訂。CSS 變數的值透過 Sass 設定,因此 Sass 自訂仍然受到支援。

--#{$prefix}modal-zindex: #{$zindex-modal};
--#{$prefix}modal-width: #{$modal-md};
--#{$prefix}modal-padding: #{$modal-inner-padding};
--#{$prefix}modal-margin: #{$modal-dialog-margin};
--#{$prefix}modal-color: #{$modal-content-color};
--#{$prefix}modal-bg: #{$modal-content-bg};
--#{$prefix}modal-border-color: #{$modal-content-border-color};
--#{$prefix}modal-border-width: #{$modal-content-border-width};
--#{$prefix}modal-border-radius: #{$modal-content-border-radius};
--#{$prefix}modal-box-shadow: #{$modal-content-box-shadow-xs};
--#{$prefix}modal-inner-border-radius: #{$modal-content-inner-border-radius};
--#{$prefix}modal-header-padding-x: #{$modal-header-padding-x};
--#{$prefix}modal-header-padding-y: #{$modal-header-padding-y};
--#{$prefix}modal-header-padding: #{$modal-header-padding}; // Todo in v6: Split this padding into x and y
--#{$prefix}modal-header-border-color: #{$modal-header-border-color};
--#{$prefix}modal-header-border-width: #{$modal-header-border-width};
--#{$prefix}modal-title-line-height: #{$modal-title-line-height};
--#{$prefix}modal-footer-gap: #{$modal-footer-margin-between};
--#{$prefix}modal-footer-bg: #{$modal-footer-bg};
--#{$prefix}modal-footer-border-color: #{$modal-footer-border-color};
--#{$prefix}modal-footer-border-width: #{$modal-footer-border-width};
--#{$prefix}backdrop-zindex: #{$zindex-modal-backdrop};
--#{$prefix}backdrop-bg: #{$modal-backdrop-bg};
--#{$prefix}backdrop-opacity: #{$modal-backdrop-opacity};

Sass 變數

$modal-inner-padding:               $spacer;

$modal-footer-margin-between:       .5rem;

$modal-dialog-margin:               .5rem;
$modal-dialog-margin-y-sm-up:       1.75rem;

$modal-title-line-height:           $line-height-base;

$modal-content-color:               null;
$modal-content-bg:                  var(--#{$prefix}body-bg);
$modal-content-border-color:        var(--#{$prefix}border-color-translucent);
$modal-content-border-width:        var(--#{$prefix}border-width);
$modal-content-border-radius:       var(--#{$prefix}border-radius-lg);
$modal-content-inner-border-radius: subtract($modal-content-border-radius, $modal-content-border-width);
$modal-content-box-shadow-xs:       var(--#{$prefix}box-shadow-sm);
$modal-content-box-shadow-sm-up:    var(--#{$prefix}box-shadow);

$modal-backdrop-bg:                 $black;
$modal-backdrop-opacity:            .5;

$modal-header-border-color:         var(--#{$prefix}border-color);
$modal-header-border-width:         $modal-content-border-width;
$modal-header-padding-y:            $modal-inner-padding;
$modal-header-padding-x:            $modal-inner-padding;
$modal-header-padding:              $modal-header-padding-y $modal-header-padding-x; // Keep this for backwards compatibility

$modal-footer-bg:                   null;
$modal-footer-border-color:         $modal-header-border-color;
$modal-footer-border-width:         $modal-header-border-width;

$modal-sm:                          300px;
$modal-md:                          500px;
$modal-lg:                          800px;
$modal-xl:                          1140px;

$modal-fade-transform:              translate(0, -50px);
$modal-show-transform:              none;
$modal-transition:                  transform .3s ease-out;
$modal-scale-transform:             scale(1.02);

Sass 迴圈

回應式全螢幕模態框 是透過 $breakpoints 地圖和 scss/_modal.scss 中的迴圈產生的。

@each $breakpoint in map-keys($grid-breakpoints) {
  $infix: breakpoint-infix($breakpoint, $grid-breakpoints);
  $postfix: if($infix != "", $infix + "-down", "");

  @include media-breakpoint-down($breakpoint) {
    .modal-fullscreen#{$postfix} {
      width: 100vw;
      max-width: none;
      height: 100%;
      margin: 0;

      .modal-content {
        height: 100%;
        border: 0;
        @include border-radius(0);
      }

      .modal-header,
      .modal-footer {
        @include border-radius(0);
      }

      .modal-body {
        overflow-y: auto;
      }
    }
  }
}

用法

模態框外掛會透過資料屬性或 JavaScript 依需求切換隱藏的內容。它也會覆寫預設的捲動行為,並產生一個 .modal-backdrop 來提供一個點擊區域,以便在點擊模態框外部時關閉顯示的模態框。

透過資料屬性

切換

在控制器元素(例如按鈕)上設定 data-bs-toggle="modal",並搭配 data-bs-target="#foo"href="#foo" 來鎖定特定的模態框進行切換,即可在不撰寫 JavaScript 的情況下啟用模態框。

<button type="button" data-bs-toggle="modal" data-bs-target="#myModal">Launch modal</button>

關閉

關閉可以在 模態框內的按鈕上使用 data-bs-dismiss 屬性來達成,如下所示

<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

或在 模態框外的按鈕上使用額外的 data-bs-target 來達成,如下所示

<button type="button" class="btn-close" data-bs-dismiss="modal" data-bs-target="#my-modal" aria-label="Close"></button>
雖然支援兩種關閉模態框的方法,但請記住,從模態框外部關閉不符合 ARIA 編寫實務指南對話框(模態框)模式。請自行承擔風險。

透過 JavaScript

使用一行 JavaScript 建立模態框

const myModal = new bootstrap.Modal(document.getElementById('myModal'), options)
// or
const myModalAlternative = new bootstrap.Modal('#myModal', options)

選項

由於選項可透過資料屬性或 JavaScript 傳遞,因此您可以將選項名稱附加到 data-bs-,例如 data-bs-animation="{value}"。傳遞選項時,請務必將選項名稱的類型從「camelCase」變更為「kebab-case」。例如,使用 data-bs-custom-class="beautifier",而非 data-bs-customClass="beautifier"

從 Bootstrap 5.2.0 開始,所有元件都支援一個實驗性的保留資料屬性 data-bs-config,該屬性可將簡單的元件設定儲存在 JSON 字串中。當元素具有 data-bs-config='{"delay":0, "title":123}'data-bs-title="456" 屬性時,最後的 title 值將為 456,而個別資料屬性將覆寫 data-bs-config 中提供的數值。此外,現有的資料屬性可以儲存 JSON 值,例如 data-bs-delay='{"show":0,"hide":150}'

最後的設定物件是 data-bs-configdata-bs-js 物件 的合併結果,其中最新提供的金鑰值會覆寫其他值。

名稱 類型 預設 說明
backdrop 布林值、'static' true 包含 modal-backdrop 元素。或者,指定 static 以取得點擊時不會關閉 modal 的背景。
focus 布林值 true 初始化時將焦點放在 modal 上。
keyboard 布林值 true 按下 escape 鍵時關閉 modal。

方法

所有 API 方法都是非同步的,並會開始轉換。它們在轉換開始後立即傳回呼叫者,但在轉換結束前。此外,將會忽略對轉換中元件的方法呼叫。 在我們的 JavaScript 文件中深入了解。

傳遞選項

將您的內容做為模態視窗啟用。接受一個選用的選項 object

const myModal = new bootstrap.Modal('#myModal', {
  keyboard: false
})
方法 說明
dispose 銷毀元素的模態視窗。(移除 DOM 元素上儲存的資料)
getInstance 靜態方法,讓您可以取得與 DOM 元素關聯的模態視窗實例。
getOrCreateInstance 靜態方法,讓您可以取得與 DOM 元素關聯的模態視窗實例,或是在尚未初始化的情況下建立一個新的實例。
handleUpdate 在模態視窗開啟時,如果模態視窗的高度改變(例如出現捲軸條),手動重新調整模態視窗的位置。
hide 手動隱藏模態視窗。在模態視窗實際隱藏之前傳回呼叫者(例如在 hidden.bs.modal 事件發生之前)。
show 手動開啟模態視窗。在模態視窗實際顯示之前傳回呼叫者(例如在 shown.bs.modal 事件發生之前)。此外,您可以傳遞一個 DOM 元素作為參數,該參數可以在模態視窗事件中接收(作為 relatedTarget 屬性)。(例如 const modalToggle = document.getElementById('toggleMyModal'); myModal.show(modalToggle)
toggle 手動切換模態視窗。在模態視窗實際顯示或隱藏之前傳回呼叫者(例如在 shown.bs.modalhidden.bs.modal 事件發生之前)。

事件

Bootstrap 的模態視窗類別提供了一些事件,用於連結到模態視窗功能。所有模態視窗事件都在模態視窗本身觸發(例如在 <div class="modal">)。

事件 說明
hide.bs.modal 當呼叫 hide 實例方法時,會立即觸發此事件。
hidden.bs.modal 當 modal 已完成對使用者隱藏時觸發此事件(會等待 CSS 轉場完成)。
hidePrevented.bs.modal 當 modal 顯示、其背景為 static 且在 modal 外部執行點擊時觸發此事件。當按下 escape 鍵且 keyboard 選項設為 false 時也會觸發此事件。
show.bs.modal 當呼叫 show 執行個體方法時,此事件會立即觸發。如果由點擊造成,則點擊的元素可用作事件的 relatedTarget 屬性。
shown.bs.modal 當 modal 已對使用者顯示時觸發此事件(會等待 CSS 轉場完成)。如果由點擊造成,則點擊的元素可用作事件的 relatedTarget 屬性。
const myModalEl = document.getElementById('myModal')
myModalEl.addEventListener('hidden.bs.modal', event => {
  // do something...
})