Skip to main content Skip to docs navigation

吐司

通过 Toast 向访客推送通知,这是一条轻量且易于定制的警报消息。

Toast 是轻量级通知,旨在模仿移动和桌面操作系统流行的推送通知。它们易于对齐和定位。

¥Toasts are lightweight notifications designed to mimic the push notifications that have been popularized by mobile and desktop operating systems. They’re built with flexbox, so they’re easy to align and position.

概述

¥Overview

使用 toast 插件时需要注意的事项:

¥Things to know when using the toast plugin:

  • 出于性能原因,Toast 是选择加入的,因此你必须自行初始化它们。

    ¥Toasts are opt-in for performance reasons, so you must initialize them yourself.

  • 如果你不指定 autohide: false,Toast 将自动隐藏。

    ¥Toasts will automatically hide if you do not specify autohide: false.

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

示例

¥Examples

基本的

¥Basic

为了鼓励可扩展和可预测的 toast,我们建议使用 header 和 body。Toast 标题使用 display: flex,借助我们的边距和 Flexbox 工具,可以轻松对齐内容。

¥To encourage extensible and predictable toasts, we recommend a header and body. Toast headers use display: flex, allowing easy alignment of content thanks to our margin and flexbox utilities.

Toast 可以根据你的需要灵活调整,并且所需的标记很少。我们至少需要一个元素来包含你的 “toasted” 内容,并强烈鼓励使用关闭按钮。

¥Toasts are as flexible as you need and have very little required markup. At a minimum, we require a single element to contain your “toasted” content and strongly encourage a dismiss button.

html
<div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="toast-header">
    <img src="..." class="rounded me-2" alt="...">
    <strong class="me-auto">Bootstrap</strong>
    <small>11 mins ago</small>
    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
  <div class="toast-body">
    Hello, world! This is a toast message.
  </div>
</div>
Previously, our scripts dynamically added the .hide class to completely hide a toast (with display:none, rather than just with opacity:0). This is now not necessary anymore. However, for backwards compatibility, our script will continue to toggle the class (even though there is no practical need for it) until the next major version.

在线示例

¥Live example

单击下面的按钮可显示默认隐藏的 Toast(位于右下角的工具中)。

¥Click the button below to show a toast (positioned with our utilities in the lower right corner) that has been hidden by default.

<button type="button" class="btn btn-primary" id="liveToastBtn">Show live toast</button>

<div class="toast-container position-fixed bottom-0 end-0 p-3">
  <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <img src="..." class="rounded me-2" alt="...">
      <strong class="me-auto">Bootstrap</strong>
      <small>11 mins ago</small>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-body">
      Hello, world! This is a toast message.
    </div>
  </div>
</div>

我们使用以下 JavaScript 来触发我们的实时吐司演示:

¥We use the following JavaScript to trigger our live toast demo:

const toastTrigger = document.getElementById('liveToastBtn')
const toastLiveExample = document.getElementById('liveToast')

if (toastTrigger) {
  const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastLiveExample)
  toastTrigger.addEventListener('click', () => {
    toastBootstrap.show()
  })
}

半透明

¥Translucent

吐司稍微半透明,可以与下面的东西融为一体。

¥Toasts are slightly translucent to blend in with what’s below them.

html
<div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="toast-header">
    <img src="..." class="rounded me-2" alt="...">
    <strong class="me-auto">Bootstrap</strong>
    <small class="text-body-secondary">11 mins ago</small>
    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
  <div class="toast-body">
    Hello, world! This is a toast message.
  </div>
</div>

堆叠

¥Stacking

你可以通过将吐司封装在吐司容器中来堆叠吐司,这会在垂直方向上增加一些间距。

¥You can stack toasts by wrapping them in a toast container, which will vertically add some spacing.

html
<div class="toast-container position-static">
  <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <img src="..." class="rounded me-2" alt="...">
      <strong class="me-auto">Bootstrap</strong>
      <small class="text-body-secondary">just now</small>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-body">
      See? Just like this.
    </div>
  </div>

  <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <img src="..." class="rounded me-2" alt="...">
      <strong class="me-auto">Bootstrap</strong>
      <small class="text-body-secondary">2 seconds ago</small>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-body">
      Heads up, toasts will stack automatically
    </div>
  </div>
</div>

定制内容

¥Custom content

通过删除子组件、使用 utilities 调整它们或添加你自己的标记来自定义你的 toast。在这里,我们通过删除默认的 .toast-header、从 Bootstrap Icons 添加自定义隐藏图标,并使用一些 flexbox 实用程序 来调整布局,创建了一个更简单的 toast。

¥Customize your toasts by removing sub-components, tweaking them with utilities, or by adding your own markup. Here we’ve created a simpler toast by removing the default .toast-header, adding a custom hide icon from Bootstrap Icons, and using some flexbox utilities to adjust the layout.

html
<div class="toast align-items-center" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="d-flex">
    <div class="toast-body">
      Hello, world! This is a toast message.
    </div>
    <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
</div>

或者,你还可以向 Toast 添加其他控件和组件。

¥Alternatively, you can also add additional controls and components to toasts.

html
<div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="toast-body">
    Hello, world! This is a toast message.
    <div class="mt-2 pt-2 border-top">
      <button type="button" class="btn btn-primary btn-sm">Take action</button>
      <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="toast">Close</button>
    </div>
  </div>
</div>

配色方案

¥Color schemes

在上面的示例的基础上,你可以使用我们的 颜色背景 实用程序创建不同的 Toast 颜色方案。在这里,我们将 .text-bg-primary 添加到 .toast,然后将 .btn-close-white 添加到我们的关闭按钮。为了获得清晰的边缘,我们使用 .border-0 删除默认边框。

¥Building on the above example, you can create different toast color schemes with our color and background utilities. Here we’ve added .text-bg-primary to the .toast, and then added .btn-close-white to our close button. For a crisp edge, we remove the default border with .border-0.

html
<div class="toast align-items-center text-bg-primary border-0" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="d-flex">
    <div class="toast-body">
      Hello, world! This is a toast message.
    </div>
    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
</div>

放置

¥Placement

根据需要使用自定义 CSS 放置 toast。右上角和中上方通常用于通知。如果你一次只想展示一个吐司词,请将定位样式放在 .toast 的右侧。

¥Place toasts with custom CSS as you need them. The top right is often used for notifications, as is the top middle. If you’re only ever going to show one toast at a time, put the positioning styles right on the .toast.

Bootstrap 11 mins ago
Hello, world! This is a toast message.
html
<form>
  <div class="mb-3">
    <label for="selectToastPlacement">Toast placement</label>
    <select class="form-select mt-2" id="selectToastPlacement">
      <option value="" selected>Select a position...</option>
      <option value="top-0 start-0">Top left</option>
      <option value="top-0 start-50 translate-middle-x">Top center</option>
      <option value="top-0 end-0">Top right</option>
      <option value="top-50 start-0 translate-middle-y">Middle left</option>
      <option value="top-50 start-50 translate-middle">Middle center</option>
      <option value="top-50 end-0 translate-middle-y">Middle right</option>
      <option value="bottom-0 start-0">Bottom left</option>
      <option value="bottom-0 start-50 translate-middle-x">Bottom center</option>
      <option value="bottom-0 end-0">Bottom right</option>
    </select>
  </div>
</form>
<div aria-live="polite" aria-atomic="true" class="bg-body-secondary position-relative bd-example-toasts rounded-3">
  <div class="toast-container p-3" id="toastPlacement">
    <div class="toast">
      <div class="toast-header">
        <img src="..." class="rounded me-2" alt="...">
        <strong class="me-auto">Bootstrap</strong>
        <small>11 mins ago</small>
      </div>
      <div class="toast-body">
        Hello, world! This is a toast message.
      </div>
    </div>
  </div>
</div>

对于生成更多通知的系统,请考虑使用封装元素,以便它们可以轻松堆叠。

¥For systems that generate more notifications, consider using a wrapping element so they can easily stack.

html
<div aria-live="polite" aria-atomic="true" class="position-relative">
  <!-- Position it: -->
  <!-- - `.toast-container` for spacing between toasts -->
  <!-- - `top-0` & `end-0` to position the toasts in the upper right corner -->
  <!-- - `.p-3` to prevent the toasts from sticking to the edge of the container  -->
  <div class="toast-container top-0 end-0 p-3">

    <!-- Then put toasts within -->
    <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
      <div class="toast-header">
        <img src="..." class="rounded me-2" alt="...">
        <strong class="me-auto">Bootstrap</strong>
        <small class="text-body-secondary">just now</small>
        <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
      <div class="toast-body">
        See? Just like this.
      </div>
    </div>

    <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
      <div class="toast-header">
        <img src="..." class="rounded me-2" alt="...">
        <strong class="me-auto">Bootstrap</strong>
        <small class="text-body-secondary">2 seconds ago</small>
        <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
      <div class="toast-body">
        Heads up, toasts will stack automatically
      </div>
    </div>
  </div>
</div>

你还可以使用 Flexbox 工具来水平和/或垂直对齐 Toast。

¥You can also get fancy with flexbox utilities to align toasts horizontally and/or vertically.

html
<!-- Flexbox container for aligning the toasts -->
<div aria-live="polite" aria-atomic="true" class="d-flex justify-content-center align-items-center w-100">

  <!-- Then put toasts within -->
  <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <img src="..." class="rounded me-2" alt="...">
      <strong class="me-auto">Bootstrap</strong>
      <small>11 mins ago</small>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-body">
      Hello, world! This is a toast message.
    </div>
  </div>
</div>

无障碍

¥Accessibility

Toast 的目的是对访问者或用户造成小干扰,因此为了帮助那些使用屏幕阅读器和类似辅助技术的人,你应该将 Toast 封装在 aria-live 地区 中。屏幕阅读器会自动宣布活动区域的更改(例如注入/更新 toast 组件),而无需移动用户的焦点或以其他方式打断用户。此外,包括 aria-atomic="true" 以确保整个 toast 始终被声明为单个(原子)单元,而不是仅仅声明更改的内容(如果你只更新 toast 的部分内容,或者如果在稍后的时间点显示相同的 toast 内容,则可能会导致问题)。如果所需的信息对于流程很重要,例如 要获取表单中的错误列表,请使用 警报组件 而不是 toast。

¥Toasts are intended to be small interruptions to your visitors or users, so to help those with screen readers and similar assistive technologies, you should wrap your toasts in an aria-live region. Changes to live regions (such as injecting/updating a toast component) are automatically announced by screen readers without needing to move the user’s focus or otherwise interrupt the user. Additionally, include aria-atomic="true" to ensure that the entire toast is always announced as a single (atomic) unit, rather than just announcing what was changed (which could lead to problems if you only update part of the toast’s content, or if displaying the same toast content at a later point in time). If the information needed is important for the process, e.g. for a list of errors in a form, then use the alert component instead of toast.

请注意,在生成或更新 toast 之前,活动区域需要出现在标记中。如果你同时动态生成两者并将它们注入到页面中,则辅助技术通常不会宣布它们。

¥Note that the live region needs to be present in the markup before the toast is generated or updated. If you dynamically generate both at the same time and inject them into the page, they will generally not be announced by assistive technologies.

你还需要根据内容调整 rolearia-live 级别。如果是错误等重要消息,请使用 role="alert" aria-live="assertive",否则使用 role="status" aria-live="polite" 属性。

¥You also need to adapt the role and aria-live level depending on the content. If it’s an important message like an error, use role="alert" aria-live="assertive", otherwise use role="status" aria-live="polite" attributes.

当你显示的内容发生变化时,请务必更新 delay 超时,以便用户有足够的时间阅读 toast。

¥As the content you’re displaying changes, be sure to update the delay timeout so that users have enough time to read the toast.

<div class="toast" role="alert" aria-live="polite" aria-atomic="true" data-bs-delay="10000">
  <div role="alert" aria-live="assertive" aria-atomic="true">...</div>
</div>

使用 autohide: false 时,你必须添加一个关闭按钮以允许用户关闭 toast。

¥When using autohide: false, you must add a close button to allow users to dismiss the toast.

html
<div role="alert" aria-live="assertive" aria-atomic="true" class="toast" data-bs-autohide="false">
  <div class="toast-header">
    <img src="..." class="rounded me-2" alt="...">
    <strong class="me-auto">Bootstrap</strong>
    <small>11 mins ago</small>
    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
  <div class="toast-body">
    Hello, world! This is a toast message.
  </div>
</div>

虽然从技术上讲,可以在 Toast 中添加可聚焦/可操作的控件(例如附加按钮或链接),但你应该避免对自动隐藏 Toast 执行此操作。即使你给吐司一个较长的 delay 超时,键盘和辅助技术用户也可能会发现很难及时到达吐司以采取行动(因为吐司在显示时不会获得焦点)。如果你绝对必须进行进一步的控制,我们建议使用 autohide: false 的吐司。

¥While technically it’s possible to add focusable/actionable controls (such as additional buttons or links) in your toast, you should avoid doing this for autohiding toasts. Even if you give the toast a long delay timeout, keyboard and assistive technology users may find it difficult to reach the toast in time to take action (since toasts don’t receive focus when they are displayed). If you absolutely must have further controls, we recommend using a toast with autohide: false.

CSS

变量

¥Variables

Added in v5.2.0

作为 Bootstrap 不断发展的 CSS 变量方法的一部分,Toast 现在使用 .toast 上的本地 CSS 变量来增强实时自定义。CSS 变量的值是通过 Sass 设置的,因此仍然支持 Sass 自定义。

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

--#{$prefix}toast-zindex: #{$zindex-toast};
--#{$prefix}toast-padding-x: #{$toast-padding-x};
--#{$prefix}toast-padding-y: #{$toast-padding-y};
--#{$prefix}toast-spacing: #{$toast-spacing};
--#{$prefix}toast-max-width: #{$toast-max-width};
@include rfs($toast-font-size, --#{$prefix}toast-font-size);
--#{$prefix}toast-color: #{$toast-color};
--#{$prefix}toast-bg: #{$toast-background-color};
--#{$prefix}toast-border-width: #{$toast-border-width};
--#{$prefix}toast-border-color: #{$toast-border-color};
--#{$prefix}toast-border-radius: #{$toast-border-radius};
--#{$prefix}toast-box-shadow: #{$toast-box-shadow};
--#{$prefix}toast-header-color: #{$toast-header-color};
--#{$prefix}toast-header-bg: #{$toast-header-background-color};
--#{$prefix}toast-header-border-color: #{$toast-header-border-color};

Sass 变量

¥Sass variables

$toast-max-width:                   350px;
$toast-padding-x:                   .75rem;
$toast-padding-y:                   .5rem;
$toast-font-size:                   .875rem;
$toast-color:                       null;
$toast-background-color:            rgba(var(--#{$prefix}body-bg-rgb), .85);
$toast-border-width:                var(--#{$prefix}border-width);
$toast-border-color:                var(--#{$prefix}border-color-translucent);
$toast-border-radius:               var(--#{$prefix}border-radius);
$toast-box-shadow:                  var(--#{$prefix}box-shadow);
$toast-spacing:                     $container-padding-x;

$toast-header-color:                var(--#{$prefix}secondary-color);
$toast-header-background-color:     rgba(var(--#{$prefix}body-bg-rgb), .85);
$toast-header-border-color:         $toast-border-color;

用法

¥Usage

通过 JavaScript 初始化 toast:

¥Initialize toasts via JavaScript:

const toastElList = document.querySelectorAll('.toast')
const toastList = [...toastElList].map(toastEl => new bootstrap.Toast(toastEl, option))

触发器

¥Triggers

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

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

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

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

选项

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

Name Type Default Description
animation boolean true Apply a CSS fade transition to the toast.
autohide boolean true Automatically hide the toast after the delay.
delay number 5000 Delay in milliseconds before hiding the toast.

方法

¥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.
Method Description
dispose Hides an element’s toast. Your toast will remain on the DOM but won’t show anymore.
getInstance Static method which allows you to get the toast instance associated with a DOM element.
For example: const myToastEl = document.getElementById('myToastEl') const myToast = bootstrap.Toast.getInstance(myToastEl) Returns a Bootstrap toast instance.
getOrCreateInstance Static method which allows you to get the toast instance associated with a DOM element, or create a new one, in case it wasn’t initialized.
const myToastEl = document.getElementById('myToastEl') const myToast = bootstrap.Toast.getOrCreateInstance(myToastEl) Returns a Bootstrap toast instance.
hide Hides an element’s toast. Returns to the caller before the toast has actually been hidden (i.e. before the hidden.bs.toast event occurs). You have to manually call this method if you made autohide to false.
isShown Returns a boolean according to toast’s visibility state.
show Reveals an element’s toast. Returns to the caller before the toast has actually been shown (i.e. before the shown.bs.toast event occurs). You have to manually call this method, instead your toast won’t show.

活动

¥Events

Event Description
hide.bs.toast This event is fired immediately when the hide instance method has been called.
hidden.bs.toast This event is fired when the toast has finished being hidden from the user.
show.bs.toast This event fires immediately when the show instance method is called.
shown.bs.toast This event is fired when the toast has been made visible to the user.
const myToastEl = document.getElementById('myToast')
myToastEl.addEventListener('hidden.bs.toast', () => {
  // do something...
})