Skip to main content Skip to docs navigation

工具提示

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

概述

🌐 Overview

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

🌐 Things to know when using the tooltip plugin:

  • 工具提示依赖第三方库 Popper 来定位。你必须在 bootstrap.js 之前包含 popper.min.js,或者使用包含 Popper 的 bootstrap.bundle.min.js
  • 出于性能原因,工具提示是可选择加入的,因此你必须自己初始化它们
  • 标题长度为零的工具提示永远不会显示。
  • 指定 container: 'body' 以避免在更复杂的组件(如我们的输入组、按钮组等)中出现渲染问题。
  • 在隐藏元素上触发工具提示将不起作用。
  • .disableddisabled 元素的工具提示必须在封装元素上触发。
  • 当从跨多行的超链接触发时,工具提示将会居中。请在你的 <a> 上使用 white-space: nowrap; 以避免此行为。
  • 在从 DOM 中删除相应的元素之前,必须隐藏工具提示。
  • 由于 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="默认工具提示">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
</button>
<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="right" data-bs-title="右侧提示">
  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
</button>
<button type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="left" data-bs-title="左侧提示">
  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>工具提示</em> <u>与</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

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 元素上(例如链接或表单控件)。虽然其他 HTML 元素可以通过添加 tabindex="0" 使其可聚焦,但这可能会在非交互元素上为键盘用户创建烦人且令人困惑的 Tab 停靠点,而且大多数辅助技术在这种情况下不会宣布工具提示。此外,不要仅依赖 hover 作为工具提示的触发方式,因为这会使其对键盘用户无法触发。

<!-- HTML to write -->
<a href="#" data-bs-toggle="tooltip" data-bs-title="一些工具提示文本!">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 选项。

NameTypeDefaultDescription
allowListobjectDefault valueAn object containing allowed tags and attributes. Those not explicitly allowed will be removed by the content sanitizer.
Exercise caution when adding to this list. Refer to OWASP’s Cross Site Scripting Prevention Cheat Sheet for more information.
animationbooleantrueApply a CSS fade transition to the tooltip.
boundarystring, element'clippingParents'Overflow constraint boundary of the tooltip (applies only to Popper’s preventOverflow modifier). By default, it’s 'clippingParents' and can accept an HTMLElement reference (via JavaScript only). For more information refer to Popper’s detectOverflow docs.
containerstring, element, falsefalseAppends the tooltip to a specific element. Example: container: 'body'. This option is particularly useful in that it allows you to position the tooltip in the flow of the document near the triggering element - which will prevent the tooltip from floating away from the triggering element during a window resize.
customClassstring, function''Add classes to the tooltip when it is shown. Note that these classes will be added in addition to any classes specified in the template. To add multiple classes, separate them with spaces: 'class-1 class-2'. You can also pass a function that should return a single string containing additional class names.
delaynumber, object0Delay showing and hiding the tooltip (ms)—doesn’t apply to manual trigger type. If a number is supplied, delay is applied to both hide/show. Object structure is: delay: { "show": 500, "hide": 100 }.
fallbackPlacementsarray['top', 'right', 'bottom', 'left']Define fallback placements by providing a list of placements in array (in order of preference). For more information refer to Popper’s behavior docs.
htmlbooleanfalseAllow HTML in the tooltip. If true, HTML tags in the tooltip’s title will be rendered in the tooltip. If false, innerText property will be used to insert content into the DOM. Prefer text when dealing with user-generated input to prevent XSS attacks.
offsetarray, string, function[0, 6]Offset of the tooltip relative to its target. You can pass a string in data attributes with comma separated values like: data-bs-offset="10,20". When a function is used to determine the offset, it is called with an object containing the popper placement, the reference, and popper rects as its first argument. The triggering element DOM node is passed as the second argument. The function must return an array with two numbers: skidding, distance. For more information refer to Popper’s offset docs.
placementstring, function'top'How to position the tooltip: auto, top, bottom, left, right. When auto is specified, it will dynamically reorient the tooltip. When a function is used to determine the placement, it is called with the tooltip DOM node as its first argument and the triggering element DOM node as its second. The this context is set to the tooltip instance.
popperConfignull, object, functionnullTo change Bootstrap’s default Popper config, see Popper’s configuration. When a function is used to create the Popper configuration, it’s called with an object that contains the Bootstrap’s default Popper configuration. It helps you use and merge the default with your own configuration. The function must return a configuration object for Popper.
sanitizebooleantrueEnable content sanitization. If true, the template, content and title options will be sanitized.
Exercise caution when disabling content sanitization. Refer to OWASP’s Cross Site Scripting Prevention Cheat Sheet for more information. Vulnerabilities caused solely by disabling content sanitization are not considered within scope for Bootstrap’s security model.
sanitizeFnnull, functionnullProvide an alternative content sanitization function. This can be useful if you prefer to use a dedicated library to perform sanitization.
selectorstring, falsefalseIf a selector is provided, tooltip objects will be delegated to the specified targets. In practice, this is used to also apply tooltips to dynamically added DOM elements (jQuery.on support). See this issue and an informative example. Note: title attribute must not be used as a selector.
templatestring'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'Base HTML to use when creating the tooltip. The tooltip’s title will be injected into the .tooltip-inner. .tooltip-arrow will become the tooltip’s arrow. The outermost wrapper element should have the .tooltip class and role="tooltip".
titlestring, element, function''The tooltip title. If a function is given, it will be called with its this reference set to the element that the popover is attached to.
triggerstring'hover focus'How tooltip is triggered: click, hover, focus, manual. You may pass multiple triggers; separate them with a space. 'manual' indicates that the tooltip will be triggered programmatically via the .tooltip('show'), .tooltip('hide') and .tooltip('toggle') methods; this value cannot be combined with any other trigger. 'hover' on its own will result in tooltips that cannot be triggered via the keyboard, and should only be used if alternative methods for conveying the same information for keyboard users is present.

单个工具提示的数据属性

🌐 Data attributes for individual tooltips

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

使用带有 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.

MethodDescription
disableRemoves the ability for an element’s tooltip to be shown. The tooltip will only be able to be shown if it is re-enabled.
disposeHides and destroys an element’s tooltip (Removes stored data on the DOM element). Tooltips that use delegation (which are created using the selector option) cannot be individually destroyed on descendant trigger elements.
enableGives an element’s tooltip the ability to be shown. Tooltips are enabled by default.
getInstanceStatic method which allows you to get the tooltip instance associated with a DOM element.
getOrCreateInstanceStatic method which allows you to get the tooltip instance associated with a DOM element, or create a new one in case it wasn’t initialized.
hideHides an element’s tooltip. Returns to the caller before the tooltip has actually been hidden (i.e. before the hidden.bs.tooltip event occurs). This is considered a “manual” triggering of the tooltip.
setContentGives a way to change the tooltip’s content after its initialization.
showReveals an element’s tooltip. Returns to the caller before the tooltip has actually been shown (i.e. before the shown.bs.tooltip event occurs). This is considered a “manual” triggering of the tooltip. Tooltips with zero-length titles are never displayed.
toggleToggles an element’s tooltip. Returns to the caller before the tooltip has actually been shown or hidden (i.e. before the shown.bs.tooltip or hidden.bs.tooltip event occurs). This is considered a “manual” triggering of the tooltip.
toggleEnabledToggles the ability for an element’s tooltip to be shown or hidden.
updateUpdates the position of an element’s tooltip.
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

事件

🌐 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()