跳到主要内容

使用 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 媒体查询。请参阅我们的无障碍文档中的减少动画部分。

继续阅读以获取演示和使用指南。

示例

下面是一个静态模态示例(意味着其position和display已被覆盖)。包括模态头部、模态主体(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>

使用网格

在模态框中使用 Bootstrap 网格系统,通过将 .container-fluid 嵌套在 .modal-body 中。然后,像在其他任何地方一样使用常规的网格系统类。

<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.relatedTarget 和 HTML 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.
<span class="token comment">// Update the modal's content.</span>
<span class="token keyword">const</span> modalTitle <span class="token operator">=</span> exampleModal<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span><span class="token string">'.modal-title'</span><span class="token punctuation">)</span>
<span class="token keyword">const</span> modalBodyInput <span class="token operator">=</span> exampleModal<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span><span class="token string">'.modal-body input'</span><span class="token punctuation">)</span>

modalTitle<span class="token punctuation">.</span>textContent <span class="token operator">=</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">New message to </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>recipient<span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span>
modalBodyInput<span class="token punctuation">.</span>value <span class="token operator">=</span> recipient

}) }

在模态之间切换

通过巧妙地设置data-bs-target和data-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-dialog 在模态淡入动画之前的变换状态,$modal-show-transform 变量决定了 .modal-dialog 在模态淡入动画结束时的变换。

例如,如果你想要一个缩放动画,你可以设置$modal-fade-transform: scale(.8)。

移除动画

对于只是出现而不是淡入显示的模态框,请从你的模态框标记中移除 .fade 类。

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

动态高度

如果模态框在打开时高度发生变化,你应该调用 myModal.handleUpdate() 来重新调整模态框的位置,以防出现滚动条。

无障碍访问

务必添加 aria-labelledby="...",参考模态标题,至 .modal此外,你还可以给出你的模态框的描述 aria-describedby 开 .modal. 请注意,你不需要添加 role="dialog" 因为我们已经通过 JavaScript 添加了它。

嵌入 YouTube 视频

在模态框中嵌入 YouTube 视频需要额外的 JavaScript(Bootstrap 中没有),以自动停止播放等功能。请参阅此有用的 Stack Overflow 帖子了解更多信息。

可选尺寸

模态框有三种可选尺寸,可通过修改类应用于 .modal-dialog。这些尺寸会在特定的断点生效,以避免在较窄的视口上出现水平滚动条。

尺寸类名模态框最大宽度
小.modal-sm300px
默认无500px
大.modal-lg800px
超大.modal-xl1140px

我们默认的不带修饰类的模态框构成了“中等”大小的模态框。

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

全屏模态

另一个覆盖选项是弹出覆盖用户视口的模态框,这可以通过放置在.modal-dialog上的修饰类来实现。

类名可用性
.modal-fullscreen始终
.modal-fullscreen-sm-down576px
.modal-fullscreen-md-down768px
.modal-fullscreen-lg-down992px
.modal-fullscreen-xl-down1200px
.modal-fullscreen-xxl-down1400px
<!-- Full screen modal -->
<div class="modal-dialog modal-fullscreen-sm-down">
  ...
</div>

CSS

变量

在 v5.2.0 中添加

作为 Bootstrap 不断发展的 CSS 变量方法的一部分,模态框现在在 .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: var(--#{$prefix}body-color); $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;

  <span class="token selector">.modal-content </span><span class="token punctuation">{</span>
    <span class="token property">height</span><span class="token punctuation">:</span> 100%<span class="token punctuation">;</span>
    <span class="token property">border</span><span class="token punctuation">:</span> 0<span class="token punctuation">;</span>
    <span class="token keyword">@include</span> <span class="token function">border-radius</span><span class="token punctuation">(</span>0<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

  <span class="token selector">.modal-header,
  .modal-footer </span><span class="token punctuation">{</span>
    <span class="token keyword">@include</span> <span class="token function">border-radius</span><span class="token punctuation">(</span>0<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>

  <span class="token selector">.modal-body </span><span class="token punctuation">{</span>
    <span class="token property">overflow-y</span><span class="token punctuation">:</span> auto<span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

} }

用法

模态插件通过数据属性或 JavaScript 按需切换隐藏内容。它还会覆盖默认的滚动行为,并生成一个 .modal-backdrop 以提供点击区域,当点击模态之外时用于关闭显示的模态。

通过数据属性

切换

在不编写 JavaScript 的情况下激活模态框。在控制元素(如按钮)上设置 data-bs-toggle="modal",并配合 data-bs-target="#foo" 或 href="#foo" 来指定要切换的特定模态框。

<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 上给定的值。此外,现有的数据属性也能够存放如 data-bs-delay='{"show":0,"hide":150}' 的 JSON 值。

最终的配置对象是data-bs-config、data-bs-和js object合并的结果,其中最新提供的键值会覆盖其他键值。

名称类型默认值描述
backdrop布尔值, ’static'true包含一个 modal-backdrop 元素。或者,指定 static 以创建点击时不关闭模态框的背景。
focusbooleantrue初始化时将焦点放在模态框上。
keyboardbooleantrue按下 Escape 键时关闭模态框。

方法

所有 API 方法都是异步的并启动一次过渡。 它们在过渡开始后立即返回给调用者,但在过渡结束之前。此外,对正在过渡的组件进行的方法调用将被忽略。 在我们的 JavaScript 文档中了解更多信息。

传球选项

将你的内容激活为模态框。可接受可选参数 options 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.modal 或者 hidden.bs.modal 事件发生)。

事件

Bootstrap 的模态框类提供了一些事件,用于挂钩模态框功能。所有模态框事件都在模态框本身触发(即在 <div class="modal">)。

事件描述
hide.bs.modal当……时,此事件会立即触发 hide 实例方法已被调用。可以通过调用来防止 event.preventDefault(). 看 JavaScript 事件文档 有关事件预防的更多详情。
hidden.bs.modal当模态框已完成对用户的隐藏时会触发此事件(将等待 CSS 过渡完成)。
hidePrevented.bs.modal当模态框显示时,将触发此事件,其背景是 static 并且在模态框外点击时会触发该事件。当按下Esc键时也会触发该事件,并且 keyboard 选项设置为 false.
show.bs.modal当...时,此事件会立即触发 show 实例方法被调用。如果是由点击引起的,被点击的元素可以作为 relatedTarget 事件的属性。
shown.bs.modal当模态框已向用户显示时(将等待 CSS 过渡完成)会触发此事件。如果是由点击引起的,点击的元素可作为 relatedTarget 事件的属性。
const myModalEl = document.getElementById('myModal')
myModalEl.addEventListener('hidden.bs.modal', event => {
  // do something...
})