Skip to main content Skip to docs navigation

弹窗

使用 Bootstrap 的 JavaScript 模态框插件,为你的网站添加用于灯箱、用户通知或完全自定义内容的对话框。

怎么运行的

¥How it works

在开始使用 Bootstrap 的模态框组件之前,请务必阅读以下内容,因为我们的菜单选项最近有所变更。

¥Before getting started with Bootstrap’s modal component, be sure to read the following as our menu options have recently changed.

  • 模态框是使用 HTML、CSS 和 JavaScript 构建的。它们位于文档中其他所有内容之上,并从 <body> 中移除滚动条,以便模态框内容滚动。

    ¥Modals are built with HTML, CSS, and JavaScript. They’re positioned over everything else in the document and remove scroll from the <body> so that modal content scrolls instead.

  • 点击模态框“背景”将自动关闭模态框。

    ¥Clicking on the modal “backdrop” will automatically close the modal.

  • Bootstrap 一次仅支持一个模式窗口。不支持嵌套模式,因为我们认为它们会带来糟糕的用户体验。

    ¥Bootstrap only supports one modal window at a time. Nested modals aren’t supported as we believe them to be poor user experiences.

  • 模态框使用 position: fixed,有时它的渲染可能有点特殊。只要有可能,请将模态 HTML 放置在顶层位置,以避免其他元素的潜在干扰。将 .modal 嵌套在另一个固定元素中时,你可能会遇到问题。

    ¥Modals use position: fixed, which can sometimes be a bit particular about its rendering. Whenever possible, place your modal HTML in a top-level position to avoid potential interference from other elements. You’ll likely run into issues when nesting a .modal within another fixed element.

  • 再次,由于 position: fixed,在移动设备上使用模态有一些注意事项。查看我们的浏览器支持文档 了解详情。

    ¥Once again, due to position: fixed, there are some caveats with using modals on mobile devices. See our browser support docs for details.

  • 由于 HTML5 定义其语义的方式,autofocus HTML 属性 在 Bootstrap 模式中没有效果。要达到相同的效果,请使用一些自定义 JavaScript:

    ¥Due to how HTML5 defines its semantics, the autofocus HTML attribute has no effect in Bootstrap modals. To achieve the same effect, use some custom JavaScript:

const myModal = document.getElementById('myModal')
const myInput = document.getElementById('myInput')

myModal.addEventListener('shown.bs.modal', () => {
  myInput.focus()
})

The animation effect of this component is dependent on the prefers-reduced-motion media query. See the reduced motion section of our accessibility documentation.

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

¥Keep reading for demos and usage guidelines.

示例

¥Examples

模态组件

¥Modal components

下面是一个静态模态示例(意味着它的 positiondisplay 已被覆盖)。包括模态页眉、模态正文(padding 必需)和模态页脚(可选)。我们要求你尽可能在关闭操作中包含模态标题,或者提供另一个显式关闭操作。

¥Below is a static modal example (meaning its position and display have been overridden). Included are the modal header, modal body (required for padding), and modal footer (optional). We ask that you include modal headers with dismiss actions whenever possible, or provide another explicit dismiss action.

<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>。如有必要,你可以使用 字体大小实用程序 来控制标题的外观。以下所有实例均使用此方法。

¥In the above static example, we use <h5>, to avoid issues with the heading hierarchy in the documentation page. Structurally, however, a modal dialog represents its own separate document/context, so the .modal-title should ideally be an <h1>. If necessary, you can use the font size utilities to control the heading’s appearance. All the following live examples use this approach.

在线演示

¥Live demo

单击下面的按钮可切换工作模式演示。它将向下滑动并从页面顶部淡入。

¥Toggle a working modal demo by clicking the button below. It will slide down and fade in from the top of the page.

<!-- 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>

静态背景

¥Static backdrop

当背景设置为静态时,在模态外部单击时模态将不会关闭。单击下面的按钮来尝试一下。

¥When backdrop is set to static, the modal will not close when clicking outside of it. Click the button below to try it.

<!-- 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>

滚动长内容

¥Scrolling long content

当模态框对于用户的视口或设备来说太长时,它们会独立于页面本身滚动。尝试下面的演示,看看我们的意思。

¥When modals become too long for the user’s viewport or device, they scroll independent of the page itself. Try the demo below to see what we mean.

你还可以通过将 .modal-dialog-scrollable 添加到 .modal-dialog 来创建允许滚动模态主体的可滚动模态。

¥You can also create a scrollable modal that allows scrolling the modal body by adding .modal-dialog-scrollable to .modal-dialog.

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

垂直居中

¥Vertically centered

.modal-dialog-centered 添加到 .modal-dialog 以使模态垂直居中。

¥Add .modal-dialog-centered to .modal-dialog to vertically center the modal.

<!-- 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>

工具提示和弹出窗口

¥Tooltips and popovers

工具提示popovers 可以根据需要放置在模态框内。当模式关闭时,其中的任何工具提示和弹出窗口也会自动消失。

¥Tooltips and popovers can be placed within modals as needed. When modals are closed, any tooltips and popovers within are also automatically dismissed.

<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>

使用网格

¥Using the grid

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

¥Utilize the Bootstrap grid system within a modal by nesting .container-fluid within the .modal-body. Then, use the normal grid system classes as you would anywhere else.

<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>

不同的模态内容

¥Varying modal content

是否有一堆按钮都触发相同的模式,但内容略有不同?使用 event.relatedTargetHTML data-bs-* 属性 根据单击的按钮改变模式的内容。

¥Have a bunch of buttons that all trigger the same modal with slightly different contents? Use event.relatedTarget and HTML data-bs-* attributes to vary the contents of the modal depending on which button was clicked.

下面是一个在线演示,后面是 HTML 和 JavaScript 示例。如需了解更多信息,请联系 阅读模态事件文档 了解有关 relatedTarget 的详细信息。

¥Below is a live demo followed by example HTML and JavaScript. For more information, read the modal events docs for details on 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
  })
}

在模态之间切换

¥Toggle between modals

通过巧妙放置 data-bs-targetdata-bs-toggle 属性,在多个模式之间切换。例如,你可以从已打开的登录模式中切换密码重置模式。请注意,多个模式不能同时打开 - 此方法只是在两个单独的模式之间切换。

¥Toggle between multiple modals with some clever placement of the data-bs-target and data-bs-toggle attributes. For example, you could toggle a password reset modal from within an already open sign in modal. Please note multiple modals cannot be open at the same time—this method simply toggles between two separate modals.

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>

改变动画

¥Change animation

$modal-fade-transform 变量确定模态淡入动画之前 .modal-dialog 的变换状态,$modal-show-transform 变量确定模态淡入动画结束时 .modal-dialog 的变换。

¥The $modal-fade-transform variable determines the transform state of .modal-dialog before the modal fade-in animation, the $modal-show-transform variable determines the transform of .modal-dialog at the end of the modal fade-in animation.

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

¥If you want for example a zoom-in animation, you can set $modal-fade-transform: scale(.8).

删除动画

¥Remove animation

对于仅显示而不是淡入视图的模态框,请从模态标记中删除 .fade 类。

¥For modals that simply appear rather than fade in to view, remove the .fade class from your modal markup.

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

动态高度

¥Dynamic heights

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

¥If the height of a modal changes while it is open, you should call myModal.handleUpdate() to readjust the modal’s position in case a scrollbar appears.

无障碍

¥Accessibility

请务必将引用模式标题的 aria-labelledby="..." 添加到 .modal。此外,你可以在 .modal 上使用 aria-describedby 描述你的模式对话框。请注意,你不需要添加 role="dialog",因为我们已经通过 JavaScript 添加了它。

¥Be sure to add aria-labelledby="...", referencing the modal title, to .modal. Additionally, you may give a description of your modal dialog with aria-describedby on .modal. Note that you don’t need to add role="dialog" since we already add it via JavaScript.

嵌入 YouTube 视频

¥Embedding YouTube videos

在模态中嵌入 YouTube 视频需要 Bootstrap 中没有的额外 JavaScript 来自动停止播放等。请参阅这篇有用的 Stack Overflow 帖子 了解更多信息。

¥Embedding YouTube videos in modals requires additional JavaScript not in Bootstrap to automatically stop playback and more. See this helpful Stack Overflow post for more information.

可选尺寸

¥Optional sizes

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

¥Modals have three optional sizes, available via modifier classes to be placed on a .modal-dialog. These sizes kick in at certain breakpoints to avoid horizontal scrollbars on narrower viewports.

尺寸模态窗口最大宽度
Small.modal-sm300px
默认None500px
.modal-lg800px
超大.modal-xl1140px

不带修饰符类的默认模态框构成“中等”尺寸的模态框。

¥Our default modal without modifier class constitutes the “medium” size modal.

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

全屏模态

¥Fullscreen Modal

另一个覆盖是弹出一个覆盖用户视口的模式的选项,可以通过放置在 .modal-dialog 上的修改器类来使用。

¥Another override is the option to pop up a modal that covers the user viewport, available via modifier classes that are placed on a .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

变量

¥Variables

Added in v5.2.0

作为 Bootstrap 不断改进的 CSS 变量方法的一部分,模态框现在在 .modal.modal-backdrop 上使用本地 CSS 变量,以增强实时自定义功能。CSS 变量的值是通过 Sass 设置的,因此仍然支持 Sass 自定义。

¥As part of Bootstrap’s evolving CSS variables approach, modals now use local CSS variables on .modal and .modal-backdrop for enhanced real-time customization. Values for the CSS variables are set via Sass, so Sass customization is still supported, too.

--#{$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 变量

¥Sass variables

$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 循环

¥Sass loops

响应式全屏模式 是通过 $breakpoints 映射和 scss/_modal.scss 中的循环生成的。

¥Responsive fullscreen modals are generated via the $breakpoints map and a loop in 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;
      }
    }
  }
}

用法

¥Usage

模态插件通过数据属性或 JavaScript 按需切换隐藏内容。它还会覆盖默认的滚动行为并生成 .modal-backdrop 以提供单击区域,以便在单击模式外部时消除显示的模式。

¥The modal plugin toggles your hidden content on demand, via data attributes or JavaScript. It also overrides default scrolling behavior and generates a .modal-backdrop to provide a click area for dismissing shown modals when clicking outside the modal.

通过数据属性

¥Via data attributes

切换

¥Toggle

无需编写 JavaScript 即可激活模式。在控制器元素(如按钮)上设置 data-bs-toggle="modal" 以及 data-bs-target="#foo"href="#foo" 以针对要切换的特定模式。

¥Activate a modal without writing JavaScript. Set data-bs-toggle="modal" on a controller element, like a button, along with a data-bs-target="#foo" or href="#foo" to target a specific modal to toggle.

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

退出

¥Dismiss

Dismissal can be achieved with the data-bs-dismiss attribute on a button within the modal as demonstrated below:

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

or on a button outside the modal using the additional data-bs-target as demonstrated below:

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

虽然两种关闭模态窗口的方式都受支持,但请记住,从模态窗口外部关闭不符合 ARIA 创作实践指南 对话框(模态框)模式 的要求。执行此操作风险自负。

¥While both ways to dismiss a modal are supported, keep in mind that dismissing from outside a modal does not match the ARIA Authoring Practices Guide dialog (modal) pattern. Do this at your own risk.

通过 JavaScript

¥Via JavaScript

使用一行 JavaScript 创建一个模式:

¥Create a modal with a single line of JavaScript:

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

选项

¥Options

As options can be passed via data attributes or JavaScript, you can append an option name to data-bs-, as in data-bs-animation="{value}". Make sure to change the case type of the option name from “camelCase” to “kebab-case” when passing the options via data attributes. For example, use data-bs-custom-class="beautifier" instead of data-bs-customClass="beautifier".

As of Bootstrap 5.2.0, all components support an experimental reserved data attribute data-bs-config that can house simple component configuration as a JSON string. When an element has data-bs-config='{"delay":0, "title":123}' and data-bs-title="456" attributes, the final title value will be 456 and the separate data attributes will override values given on data-bs-config. In addition, existing data attributes are able to house JSON values like data-bs-delay='{"show":0,"hide":150}'.

The final configuration object is the merged result of data-bs-config, data-bs-, and js object where the latest given key-value overrides the others.

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

方法

¥Methods

All API methods are asynchronous and start a transition. They return to the caller as soon as the transition is started, but before it ends. In addition, a method call on a transitioning component will be ignored. Learn more in our JavaScript docs.

传递选项

¥Passing options

将你的内容激活为模式。接受可选选项 object

¥Activates your content as a modal. Accepts an optional 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.modalhidden.bs.modal 事件发生之前)返回给调用者。

活动

¥Events

Bootstrap 的 modal 类公开了一些事件,用于连接到模态功能。所有模态事件均在模态本身(即 <div class="modal">)处触发。

¥Bootstrap’s modal class exposes a few events for hooking into modal functionality. All modal events are fired at the modal itself (i.e. at the <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...
})