跳至主要内容 跳至文档导航

使用 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-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。此外,您可以在 .modal 上使用 aria-describedby 提供模态框对话框的描述。请注意,您无需添加 role="dialog",因为我们已通过 JavaScript 添加了它。

嵌入 YouTube 视频

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

可选尺寸

模态框有三种可选尺寸,可通过修饰符类使用,这些类应放在 .modal-dialog 上。这些尺寸在特定断点处启动,以避免在较窄的视口中出现水平滚动条。

尺寸 模态框最大宽度
.modal-sm 300px
默认 500px
.modal-lg 800px
超大 .modal-xl 1140px

我们没有修饰符类的默认模态框构成“中等”尺寸模态框。

<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-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-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,以在点击模态框外部时提供一个点击区域来关闭显示的模态框。

通过数据属性

切换

在不编写 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-dismiss 属性来实现关闭,如下所示

<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 包括一个模态背景元素。或者,为不会在单击时关闭模态的背景指定 static
focus 布尔值 true 在初始化时将焦点放在模态上。
keyboard 布尔值 true 在按下 Escape 键时关闭模态。

方法

所有 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 当模态框完成对用户隐藏时,触发此事件(将等待 CSS 过渡完成)。
hidePrevented.bs.modal 当模态框显示、其背景为 static 且在模态框外部执行单击时,触发此事件。当按下转义键且 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...
})