Skip to main content Skip to docs navigation

工具提示

使用 CSS 和 JavaScript 添加自定义 Bootstrap 工具提示的文档和示例,使用 C 进行动画和数据 bs 属性进行本地标题存储。

概述

¥Overview

使用工具提示插件时需要注意的事项:

¥Things to know when using the tooltip plugin:

  • Tooltips 依赖第三方库 Popper 进行定位。你必须在 bootstrap.js 之前包含 popper.min.js,或者使用包含 Popper 的 bootstrap.bundle.min.js

    ¥Tooltips rely on the third party library Popper for positioning. You must include popper.min.js before bootstrap.js, or use one bootstrap.bundle.min.js which contains Popper.

  • 出于性能原因,工具提示是可选的,因此你必须自行初始化它们。

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

  • 标题长度为零的工具提示永远不会显示。

    ¥Tooltips with zero-length titles are never displayed.

  • 指定 container: 'body' 以避免更复杂的组件(例如我们的输入组、按钮组等)中出现渲染问题。

    ¥Specify container: 'body' to avoid rendering problems in more complex components (like our input groups, button groups, etc).

  • 在隐藏元素上触发工具提示将不起作用。

    ¥Triggering tooltips on hidden elements will not work.

  • .disableddisabled 元素的工具提示必须在封装元素上触发。

    ¥Tooltips for .disabled or disabled elements must be triggered on a wrapper element.

  • 当从跨多行的超链接触发时,工具提示将居中。在 <a> 上使用 white-space: nowrap; 可以避免这种行为。

    ¥When triggered from hyperlinks that span multiple lines, tooltips will be centered. Use white-space: nowrap; on your <a>s to avoid this behavior.

  • 在从 DOM 中删除相应的元素之前,必须隐藏工具提示。

    ¥Tooltips must be hidden before their corresponding elements have been removed from the DOM.

  • 由于 Shadow DOM 内的元素,可以触发工具提示。

    ¥Tooltips can be triggered thanks to an element inside a shadow DOM.

明白了吗?太棒了,让我们通过一些示例看看它们是如何工作的。

¥Got all that? Great, let’s see how they work with some examples.

By default, this component uses the built-in content sanitizer, which strips out any HTML elements that are not explicitly allowed. See the sanitizer section in our JavaScript documentation for more details.

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

启用工具提示

¥Enable tooltips

如上所述,你必须先初始化工具提示才能使用它们。初始化页面上所有工具提示的一种方法是通过它们的 data-bs-toggle 属性选择它们,如下所示:

¥As mentioned above, you must initialize tooltips before they can be used. One way to initialize all tooltips on a page would be to select them by their data-bs-toggle attribute, like so:

const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]')
const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl))

链接上的工具提示

¥Tooltips on links

将鼠标悬停在下面的链接上可查看工具提示:

¥Hover over the links below to see tooltips:

Placeholder text to demonstrate some inline links with tooltips. This is now just filler, no killer. Content placed here just to mimic the presence of real text. And all that just to give you an idea of how tooltips would look when used in real-world situations. So hopefully you’ve now seen how these tooltips on links can work in practice, once you use them on your own site or project.

html
<p class="muted">Placeholder text to demonstrate some <a href="#" data-bs-toggle="tooltip" data-bs-title="Default tooltip">inline links</a> with tooltips. This is now just filler, no killer. Content placed here just to mimic the presence of <a href="#" data-bs-toggle="tooltip" data-bs-title="Another tooltip">real text</a>. And all that just to give you an idea of how tooltips would look when used in real-world situations. So hopefully you’ve now seen how <a href="#" data-bs-toggle="tooltip" data-bs-title="Another one here too">these tooltips on links</a> can work in practice, once you use them on <a href="#" data-bs-toggle="tooltip" data-bs-title="The last tip!">your own</a> site or project.</p>

Feel free to use either title or data-bs-title in your HTML. When title is used, Popper will replace it automatically with data-bs-title when the element is rendered.

自定义工具提示

¥Custom tooltips

Added in v5.2.0

你可以使用 CSS 变量 自定义工具提示的外观。我们使用 data-bs-custom-class="custom-tooltip" 设置自定义类来确定自定义外观的范围,并使用它来覆盖本地 CSS 变量。

¥You can customize the appearance of tooltips using CSS variables. We set a custom class with data-bs-custom-class="custom-tooltip" to scope our custom appearance and use it to override a local CSS variable.

.custom-tooltip {
  --bs-tooltip-bg: var(--bd-violet-bg);
  --bs-tooltip-color: var(--bs-white);
}
html
<button type="button" class="btn btn-secondary"
        data-bs-toggle="tooltip" data-bs-placement="top"
        data-bs-custom-class="custom-tooltip"
        data-bs-title="This top tooltip is themed via CSS variables.">
  Custom tooltip
</button>

方向

¥Directions

将鼠标悬停在下面的按钮上可查看四个工具提示方向:上、右、下、左。在 RTL 中使用 Bootstrap 时,方向会被镜像。

¥Hover over the buttons below to see the four tooltips directions: top, right, bottom, and left. Directions are mirrored when using Bootstrap in RTL.

<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="Tooltip on top">
  Tooltip on top
</button>
<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="right" data-bs-title="Tooltip on right">
  Tooltip on right
</button>
<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Tooltip on bottom">
  Tooltip on bottom
</button>
<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="left" data-bs-title="Tooltip on left">
  Tooltip on left
</button>

并添加自定义 HTML:

¥And with custom HTML added:

<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-html="true" data-bs-title="<em>Tooltip</em> <u>with</u> <b>HTML</b>">
  Tooltip with HTML
</button>

使用 SVG:

¥With an SVG:

CSS

变量

¥Variables

Added in v5.2.0

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

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

--#{$prefix}tooltip-zindex: #{$zindex-tooltip};
--#{$prefix}tooltip-max-width: #{$tooltip-max-width};
--#{$prefix}tooltip-padding-x: #{$tooltip-padding-x};
--#{$prefix}tooltip-padding-y: #{$tooltip-padding-y};
--#{$prefix}tooltip-margin: #{$tooltip-margin};
@include rfs($tooltip-font-size, --#{$prefix}tooltip-font-size);
--#{$prefix}tooltip-color: #{$tooltip-color};
--#{$prefix}tooltip-bg: #{$tooltip-bg};
--#{$prefix}tooltip-border-radius: #{$tooltip-border-radius};
--#{$prefix}tooltip-opacity: #{$tooltip-opacity};
--#{$prefix}tooltip-arrow-width: #{$tooltip-arrow-width};
--#{$prefix}tooltip-arrow-height: #{$tooltip-arrow-height};

Sass 变量

¥Sass variables

$tooltip-font-size:                 $font-size-sm;
$tooltip-max-width:                 200px;
$tooltip-color:                     var(--#{$prefix}body-bg);
$tooltip-bg:                        var(--#{$prefix}emphasis-color);
$tooltip-border-radius:             var(--#{$prefix}border-radius);
$tooltip-opacity:                   .9;
$tooltip-padding-y:                 $spacer * .25;
$tooltip-padding-x:                 $spacer * .5;
$tooltip-margin:                    null; // TODO: remove this in v6

$tooltip-arrow-width:               .8rem;
$tooltip-arrow-height:              .4rem;
// fusv-disable
$tooltip-arrow-color:               null; // Deprecated in Bootstrap 5.2.0 for CSS variables
// fusv-enable

用法

¥Usage

工具提示插件根据需要生成内容和标记,并默认将工具提示放置在其触发元素之后。通过 JavaScript 触发工具提示:

¥The tooltip plugin generates content and markup on demand, and by default places tooltips after their trigger element. Trigger the tooltip via JavaScript:

const exampleEl = document.getElementById('example')
const tooltip = new bootstrap.Tooltip(exampleEl, options)

当父容器具有 overflow: autooverflow: scroll 时,工具提示会自动尝试更改位置,但仍保持原始位置。将 boundary 选项(使用 popperConfig 选项的翻转修饰符)设置为任何 HTMLElement 以覆盖默认值 'clippingParents',例如 document.body

¥Tooltips automatically attempt to change positions when a parent container has overflow: auto or overflow: scroll, but still keeps the original placement’s positioning. Set the boundary option (for the flip modifier using the popperConfig option) to any HTMLElement to override the default value, 'clippingParents', such as document.body:

const tooltip = new bootstrap.Tooltip('#example', {
boundary: document.body // or document.querySelector('#boundary')
})

标记

¥Markup

工具提示所需的标记只是你希望具有工具提示的 HTML 元素上的 data 属性和 title。生成的工具提示标记相当简单,尽管它确实需要一个位置(默认情况下,由插件设置为 top)。

¥The required markup for a tooltip is only a data attribute and title on the HTML element you wish to have a tooltip. The generated markup of a tooltip is rather simple, though it does require a position (by default, set to top by the plugin).

通过仅将工具提示添加到传统上可通过键盘聚焦且可交互的 HTML 元素(例如链接或表单控件)中,确保键盘用户和辅助技术用户能够访问工具提示。虽然可以通过添加 tabindex="0" 使其他 HTML 元素可聚焦,但这会在非交互元素上为键盘用户创建恼人且令人困惑的制表位,并且大多数辅助技术目前不会在这种情况下播报工具提示。此外,不要仅仅依赖 hover 作为工具提示的触发器,因为这将使键盘用户无法触发它们。

¥Keep tooltips accessible to keyboard and assistive technology users by only adding them to HTML elements that are traditionally keyboard-focusable and interactive (such as links or form controls). While other HTML elements can be made focusable by adding tabindex="0", this can create annoying and confusing tab stops on non-interactive elements for keyboard users, and most assistive technologies currently do not announce tooltips in this situation. Additionally, do not rely solely on hover as the trigger for your tooltips as this will make them impossible to trigger for keyboard users.

<!-- HTML to write -->
<a href="#" data-bs-toggle="tooltip" data-bs-title="Some tooltip text!">Hover over me</a>

<!-- Generated markup by the plugin -->
<div class="tooltip bs-tooltip-auto" role="tooltip">
  <div class="tooltip-arrow"></div>
  <div class="tooltip-inner">
    Some tooltip text!
  </div>
</div>

禁用元素

¥Disabled elements

带有 disabled 属性的元素不具有交互性,这意味着用户无法聚焦、悬停或点击它们来触发工具提示(或弹出窗口)。作为一种解决方法,你需要从封装器 <div><span> 触发工具提示,理想情况下,使用 tabindex="0" 使其可键盘对焦。

¥Elements with the disabled attribute aren’t interactive, meaning users cannot focus, hover, or click them to trigger a tooltip (or popover). As a workaround, you’ll want to trigger the tooltip from a wrapper <div> or <span>, ideally made keyboard-focusable using tabindex="0".

html
<span class="d-inline-block" tabindex="0" data-bs-toggle="tooltip" data-bs-title="Disabled tooltip">
  <button class="btn btn-primary" type="button" disabled>Disabled button</button>
</span>

选项

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

请注意,出于安全原因,不能使用数据属性提供 sanitizesanitizeFnallowList 选项。

¥Note that for security reasons the sanitize, sanitizeFn, and allowList options cannot be supplied using data attributes.

名称类型默认描述
allowListobject默认值包含允许的属性和标签的对象。
animationbooleantrue为工具提示应用 CSS 淡入淡出过渡效果。
boundary字符串,元素'clippingParents'工具提示的溢出约束边界(仅适用于 Popper 的 preventOverflow 修饰符)。默认情况下,它是 'clippingParents',可以接受 HTMLElement 引用(仅通过 JavaScript)。有关更多信息,请参阅 Popper 的 detectOverflow 文档
container字符串,元素,falsefalse将工具提示附加到特定元素。示例:container: 'body'。此选项非常有用,因为它允许你将工具提示放置在文档流中触发元素附近。 - 这将防止工具提示在窗口调整大小时从触发元素上浮开。
customClass字符串,函数''在工具提示显示时为其添加类。请注意,除了模板中指定的任何类之外,还将添加这些类。要添加多个类,请用空格分隔:'class-1 class-2'。你还可以传递一个函数,该函数应返回包含其他类名的单个字符串。
delay数字,对象0显示和隐藏工具提示的延迟时间(毫秒) - 不适用于手动触发类型。如果指定了一个数字,则隐藏/显示都会应用延迟。对象结构如下:delay: { "show": 500, "hide": 100 }
fallbackPlacementsarray['top', 'right', 'bottom', 'left']通过提供数组中的位置列表(按优先顺序)来定义后备位置。有关更多信息,请参阅 Popper 的 行为文档
htmlbooleanfalse允许在工具提示中使用 HTML。如果设置为 true,工具提示的 title 中的 HTML 标签将会在工具提示中渲染。如果为 false,则 innerText 属性将用于将内容插入 DOM。如果你担心 XSS 攻击,请使用文本。
offset数组,字符串,函数[0, 6]工具提示相对于其目标元素的偏移量。你可以在数据属性中传递一个以逗号分隔的字符串,例如:data-bs-offset="10,20"。当使用函数确定偏移量时,会使用包含 Popper 位置、引用和 Popper 矩形的对象作为其第一个参数来调用该函数。触发元素的 DOM 节点作为第二个参数传递。该函数必须返回一个包含两个数字的数组:skidding, distance.有关更多信息,请参阅 Popper 的 偏移文档
placement字符串,函数'top'如何定位工具提示:自动、顶部、底部、左侧、右侧。指定 auto 后,它将动态重新调整工具提示的方向。当使用函数确定位置时,会使用工具提示 DOM 节点作为其第一个参数,使用触发元素 DOM 节点作为其第二个参数来调用该函数。this 上下文设置为工具提示实例。
popperConfignull,对象,函数null要更改 Bootstrap 的默认 Popper 配置,请参阅 Popper 配置。当使用函数创建 Popper 配置时,会使用包含 Bootstrap 默认 Popper 配置的对象来调用该函数。它可以帮助你使用默认配置并将其与你自己的配置合并。该函数必须返回 Popper 的配置对象。
sanitizebooleantrue启用或禁用清理功能。如果激活,'template''content''title' 选项将被过滤。
sanitizeFnnull,函数null这里你可以提供自己的清理函数。如果你更喜欢使用专用库来执行清理,这将非常有用。
selector字符串,falsefalse如果指定了选择器,工具提示对象将被委托给指定的目标。实际操作中,它也用于将工具提示应用于动态添加的 DOM 元素(支持 jQuery.on)。请参阅 此问题一个信息丰富的示例。注意:title 属性不能用作选择器。
templatestring'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'创建工具提示时使用的基本 HTML。工具提示的 title 将被注入到 .tooltip-inner 中。.tooltip-arrow 将成为工具提示的箭头。最外层的封装元素应包含 .tooltip 类和 role="tooltip" 类。
title字符串,元素,函数''工具提示标题。如果指定了一个函数,它将被调用,并将其 this 引用设置为弹出窗口所附加的元素。
triggerstring'hover focus'如何触发工具提示:点击,悬停,焦点,手动。你可以传递多个触发器;请用空格分隔它们。'manual' 表示工具提示将通过 .tooltip('show').tooltip('hide').tooltip('toggle') 方法以编程方式触发;此值不能与任何其他触发器组合使用。'hover' 本身会导致工具提示无法通过键盘触发,因此仅在存在其他方法为键盘用户传达相同信息时才应使用。

单个工具提示的数据属性

¥Data attributes for individual tooltips

也可以通过使用数据属性来指定单个工具提示的选项,如上所述。

¥Options for individual tooltips can alternatively be specified through the use of data attributes, as explained above.

将函数与 popperConfig 一起使用

¥Using function with popperConfig

const tooltip = new bootstrap.Tooltip(element, {
  popperConfig(defaultBsPopperConfig) {
    // const newPopperConfig = {...}
    // use defaultBsPopperConfig if needed...
    // return newPopperConfig
  }
})

方法

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

方法描述
disable移除了元素工具提示的显示功能。只有重新启用工具提示后才能显示。
dispose隐藏并销毁元素的工具提示(移除 DOM 元素上存储的数据)。使用委托(使用 selector 选项 创建)的工具提示无法在后代触发元素上单独销毁。
enable使元素的工具提示能够显示。工具提示默认启用。
getInstance静态方法,允许你获取与 DOM 元素关联的工具提示实例。
getOrCreateInstance静态方法,允许你获取与 DOM 元素关联的工具提示实例,或者在未初始化的情况下创建一个新的。
hide隐藏元素的工具提示。在工具提示实际隐藏之前(即,在 hidden.bs.tooltip 事件发生之前)返回给调用者。这被视为“手动”触发工具提示。
setContent提供一种在工具提示初始化后更改其内容的方法。
show显示元素的工具提示。在工具提示实际显示之前(即,在 shown.bs.tooltip 事件发生之前)返回给调用者。这被视为“手动”触发工具提示。标题长度为零的工具提示永远不会显示。
toggle切换元素的工具提示。在工具提示实际显示或隐藏之前(即,在 shown.bs.tooltiphidden.bs.tooltip 事件发生之前)返回给调用者。这被视为“手动”触发工具提示。
toggleEnabled切换元素工具提示的显示或隐藏状态。
update更新元素工具提示的位置。
const tooltip = bootstrap.Tooltip.getInstance('#example') // Returns a Bootstrap tooltip instance

// setContent example
tooltip.setContent({ '.tooltip-inner': 'another title' })

setContent 方法接受一个 object 参数,其中每个属性键都是工具提示模板中有效的 string 选择器,并且每个相关的属性值可以是 string | element | function | null

¥The setContent method accepts an object argument, where each property-key is a valid string selector within the tooltip template, and each related property-value can be string | element | function | null

活动

¥Events

事件描述
hide.bs.tooltip调用 hide 实例方法后,此事件立即触发。
hidden.bs.tooltip当工具提示完全对用户隐藏时,会触发此事件(将等待 CSS 过渡完成)。
inserted.bs.tooltip当工具提示模板添加到 DOM 时,此事件在 show.bs.tooltip 事件之后触发。
show.bs.tooltip此事件在调用 show 实例方法时立即触发。
shown.bs.tooltip当工具提示完全对用户可见时,会触发此事件(将等待 CSS 过渡完成)。
const myTooltipEl = document.getElementById('myTooltip')
const tooltip = bootstrap.Tooltip.getOrCreateInstance(myTooltipEl)

myTooltipEl.addEventListener('hidden.bs.tooltip', () => {
  // do something...
})

tooltip.hide()