Skip to main content Skip to docs navigation
View on GitHub

Tooltips工具提示

Documentation and examples for adding custom Bootstrap tooltips with CSS and JavaScript using CSS3 for animations and data-bs-attributes for local title storage.使用CSS和JavaScript添加自定义Bootstrap工具提示的文档和示例,使用CSS3为动画和数据bs属性为本地标题存储。

Overview概述

Things to know when using the tooltip plugin:使用工具提示插件时需要注意的事项:

  • Tooltips rely on the 3rd party library Popper for positioning. 工具提示依赖于第三方库Popper进行定位。You must include popper.min.js before bootstrap.js or use bootstrap.bundle.min.js / bootstrap.bundle.js which contains Popper in order for tooltips to work!您必须在bootstrap.js之前包含popper.min.js,或者使用包含Popper的bootstrap.bundle.min.js / bootstrap.bundle.js才能使工具提示工作!
  • Tooltips are opt-in for performance reasons, so you must initialize them yourself.出于性能原因,工具提示是可选的,因此您必须自己初始化它们
  • Tooltips with zero-length titles are never displayed.不显示标题长度为零的工具提示。
  • Specify container: 'body' to avoid rendering problems in more complex components (like our input groups, button groups, etc).指定container: 'body'以避免在更复杂的组件(如输入组、按钮组等)中呈现问题。
  • Triggering tooltips on hidden elements will not work.在隐藏元素上触发工具提示将不起作用。
  • Tooltips for .disabled or disabled elements must be triggered on a wrapper element.必须在包装元素上触发.disableddisabled元素的工具提示。
  • When triggered from hyperlinks that span multiple lines, tooltips will be centered. 当从跨多行的超链接触发时,工具提示将居中。Use white-space: nowrap; on your <a>s to avoid this behavior.<a>上使用white-space: nowrap;以避免这种行为。
  • Tooltips must be hidden before their corresponding elements have been removed from the DOM.在从DOM中删除相应的元素之前,必须隐藏工具提示。
  • Tooltips can be triggered thanks to an element inside a shadow DOM.由于阴影DOM中的元素,可以触发工具提示。
By default, this component uses the built-in content sanitizer, which strips out any HTML elements that are not explicitly allowed. 默认情况下,该组件使用内置的内容清理器,它会清除任何不明确允许的HTML元素。See the sanitizer section in our JavaScript documentation for more details.有关更多详细信息,请参阅JavaScript文档中的消毒剂部分
The animation effect of this component is dependent on the prefers-reduced-motion media query. 此组件的动画效果取决于prefers-reduced-motion媒体查询。See the reduced motion section of our accessibility documentation.请参阅可访问性文档中的减少运动部分

Got all that? Great, let’s see how they work with some examples.明白了吗?太好了,让我们看看他们是如何使用一些示例的。

Example: Enable tooltips everywhere示例:到处启用工具提示

One way to initialize all tooltips on a page would be to select them by their data-bs-toggle attribute:初始化页面上所有工具提示的一种方法是通过其data-bs-toggle属性选择它们:

var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl)
})

Examples示例

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.因此,希望您现在已经看到了链接上的这些工具提示在实践中是如何工作的,一旦您在自己的网站或项目上使用它们。

Hover over the buttons below to see the four tooltips directions: top, right, bottom, and left. Directions are mirrored when using Bootstrap in RTL.将鼠标悬停在下面的按钮上可查看四个工具提示方向:顶部、右侧、底部和左侧。在RTL中使用Bootstrap时,方向是镜像的。

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

And with custom HTML added:并且添加了自定义HTML:

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

With an SVG:使用SVG:

Sass

Variables变量

$tooltip-font-size:                 $font-size-sm;
$tooltip-max-width:                 200px;
$tooltip-color:                     $white;
$tooltip-bg:                        $black;
$tooltip-border-radius:             $border-radius;
$tooltip-opacity:                   .9;
$tooltip-padding-y:                 $spacer * .25;
$tooltip-padding-x:                 $spacer * .5;
$tooltip-margin:                    0;
$tooltip-arrow-width:               .8rem;
$tooltip-arrow-height:              .4rem;
$tooltip-arrow-color:               $tooltip-bg;

Usage用法

The tooltip plugin generates content and markup on demand, and by default places tooltips after their trigger element.工具提示插件按需生成内容和标记,默认情况下,将工具提示放置在触发器元素之后。

Trigger the tooltip via JavaScript:通过JavaScript触发工具提示:

var exampleEl = document.getElementById('example')
var tooltip = new bootstrap.Tooltip(exampleEl, options)
Overflow auto and scroll溢出autoscroll

Tooltip position attempts to automatically change when a parent container has overflow: auto or overflow: scroll like our .table-responsive, but still keeps the original placement’s positioning. 父容器具有overflow: autooverflow: scroll时,工具提示位置尝试自动更改,就像.table-responsive那样,但仍保持原始位置的位置。To resolve this, 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:要解决此问题,请将boundary选项(对于使用popperConfig选项的翻转修饰符)设置为任何HTMLElement,以覆盖默认值'clippingParents',如document.body

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

Markup

The required markup for a tooltip is only a data attribute and title on the HTML element you wish to have a tooltip. 工具提示所需的标记仅是希望具有工具提示的HTML元素上的data属性和titleThe generated markup of a tooltip is rather simple, though it does require a position (by default, set to top by the plugin).生成的工具提示标记相当简单,但它确实需要一个位置(默认情况下,由插件设置为top)。

Making tooltips work for keyboard and assistive technology users为键盘和辅助技术用户提供工具提示

You should only add tooltips to HTML elements that are traditionally keyboard-focusable and interactive (such as links or form controls). 您应该只将工具提示添加到HTML元素中,这些元素传统上是以键盘为焦点的和交互式的(例如链接或表单控件)。Although arbitrary HTML elements (such as <span>s) can be made focusable by adding the tabindex="0" attribute, this will add potentially annoying and confusing tab stops on non-interactive elements for keyboard users, and most assistive technologies currently do not announce the tooltip in this situation. 尽管通过添加 tabindex="0"隆隆可以使任意HTML元素(例如<span>)可聚焦,这将为键盘用户在非交互式元素上添加潜在的烦人和令人困惑的制表符,并且大多数辅助技术目前不会在这种情况下公布工具提示。Additionally, do not rely solely on hover as the trigger for your tooltip, as this will make your tooltips impossible to trigger for keyboard users.此外,不要只依赖hover作为工具提示的触发器,因为这将使键盘用户无法触发工具提示。

<!-- HTML to write -->
<a href="#" data-bs-toggle="tooltip" title="Some tooltip text!">Hover over me</a>
<!-- Generated markup by the plugin -->
<div class="tooltip bs-tooltip-top" role="tooltip">
<div class="tooltip-arrow"></div>
<div class="tooltip-inner">
Some tooltip text!
</div>
</div>

Disabled elements禁用的元素

Elements with the disabled attribute aren’t interactive, meaning users cannot focus, hover, or click them to trigger a tooltip (or popover). 具有disabled属性的元素不是交互式的,这意味着用户不能聚焦、悬停或单击它们来触发工具提示(或弹出窗口)。As a workaround, you’ll want to trigger the tooltip from a wrapper <div> or <span>, ideally made keyboard-focusable using tabindex="0".作为解决方法,您需要从包装器<div><span>触发工具提示,理想情况下,使用tabindex="0"使键盘可聚焦。

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

Options选项

Options can be passed via data attributes or JavaScript. 选项可以通过数据属性或JavaScript传递。For data attributes, append the option name to data-bs-, as in data-bs-animation="". 对于数据属性,将选项名称附加到data-bs-,如data-bs-animation=""Make sure to change the case type of the option name from camelCase to kebab-case when passing the options via data attributes. 通过数据属性传递选项时,确保将选项名称的大小写类型从camelCase更改为kebab case。For example, instead of using data-bs-customClass="beautifier", use data-bs-custom-class="beautifier".例如,不是使用data-bs-customClass="beautifier",而是使用data-bs-custom-class="beautifier"

Note that for security reasons the sanitize, sanitizeFn, and allowList options cannot be supplied using data attributes.请注意,出于安全原因,不能使用数据属性提供sanitizesanitizeFnallowList选项。
Name Type Default Description
animation boolean true Apply a CSS fade transition to the tooltip对工具提示应用CSS渐变
container string | element | false false

Appends the tooltip to a specific element. 将工具提示附加到特定元素。Example: container: 'body'. 示例: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.此选项特别有用,因为它允许您将工具提示放置在文档流中靠近触发元素的位置,这将防止工具提示在窗口调整期间从触发元素浮动。

delay number | object 0

Delay showing and hiding the tooltip (ms) - does not 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 }

html boolean false

Allow HTML in the tooltip.在工具提示中允许HTML。

If true, HTML tags in the tooltip's title will be rendered in the tooltip. 如果为true,则工具提示title中的HTML标记将在工具提示中呈现。If false, innerText property will be used to insert content into the DOM.如果为false,innerText属性将用于将内容插入DOM。

Use text if you're worried about XSS attacks.如果您担心XSS攻击,请使用文本。

placement string | function 'top'

How to position the tooltip - auto | top | bottom | left | right.
When auto is specified, it will dynamically reorient the tooltip.
如何定位工具提示-auto | top | bottom | left | right
当指定auto时,它将动态调整工具提示的方向。

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. 当函数用于确定位置时,调用该函数时,工具提示DOM节点作为其第一个参数,触发元素DOM节点作为第二个参数。The this context is set to the tooltip instance.this上下文设置为工具提示实例。

selector string | false false If 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). 实际上,这也用于将工具提示应用于动态添加的DOM元素(jQuery.on支持)。See this and an informative example.请参阅this一个信息性示例
template string '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'

Base HTML to use when creating the tooltip.创建工具提示时要使用的基本HTML。

The tooltip's title will be injected into the .tooltip-inner.title提示的标题将注入.tooltip-inner

.tooltip-arrow will become the tooltip's arrow.将成为工具提示的箭头。

The outermost wrapper element should have the .tooltip class and role="tooltip".最外层的包装器元素应该具有.tooltip类和role="tooltip"

title string | element | function ''

Default title value if title attribute isn't present.如果title属性不存在,则默认标题值。

If a function is given, it will be called with its this reference set to the element that the tooltip is attached to.如果给定了一个函数,则将调用this函数,并将其此引用设置为工具提示附加到的元素。

trigger string 'hover focus'

How tooltip is triggered - click | hover | focus | manual. 如何触发工具提示-click | hover | focus | manualYou may pass multiple triggers; separate them with a space.您可以传递多个触发器;用空格隔开它们。

'manual' indicates that the tooltip will be triggered programmatically via the .show(), .hide() and .toggle() methods; this value cannot be combined with any other trigger.指示工具提示将通过.show().hide().toggle()方法以编程方式触发;该值不能与任何其他触发器组合。

'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.'hover'本身将导致无法通过键盘触发的工具提示,并且只有在存在为键盘用户传递相同信息的替代方法时才应使用。

fallbackPlacements array ['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有关更多信息,请参阅Popper的行为文档
boundary string | element 'clippingParents' Overflow constraint boundary of the tooltip (applies only to Popper's preventOverflow modifier). 工具提示的溢出约束边界(仅适用于Popper的preventOverflow修饰符)。By default it's 'clippingParents' and can accept an HTMLElement reference (via JavaScript only). 默认情况下,它是'clippingParents',可以接受HTMLElement引用(仅通过JavaScript)。For more information refer to Popper's detectOverflow docs.有关更多信息,请参阅Popper的detectOverflow文档
customClass string | 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'.若要添加多个类,请用空格分隔它们:'class-1 class-2'

You can also pass a function that should return a single string containing additional class names.还可以传递一个函数,该函数应返回包含其他类名的单个字符串。

sanitize boolean true Enable or disable the sanitization. 启用或禁用净化。If activated 'template' and 'title' options will be sanitized. 如果激活了'template''title'选项,将被清除。See the sanitizer section in our JavaScript documentation.请参阅JavaScript文档中的消毒剂部分
allowList object Default value Object which contains allowed attributes and tags包含允许的属性和标记的对象
sanitizeFn null | function null Here you can supply your own sanitize function. 在这里,您可以提供自己的消毒功能。This can be useful if you prefer to use a dedicated library to perform sanitization.如果您希望使用专用库来执行清理,这可能很有用。
offset array | string | function [0, 0]

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. 当函数用于确定偏移量时,将使用包含popper放置、引用和popper矩形的对象作为其第一个参数来调用该函数。The triggering element DOM node is passed as the second argument. 触发元素DOM节点作为第二个参数传递。The function must return an array with two numbers: [skidding, distance].函数必须返回一个包含两个数字的数组:[skidding, distance]

For more information refer to Popper's offset docs.有关更多信息,请参阅Popper的偏移文档

popperConfig null | object | function null

To change Bootstrap's default Popper config, see Popper's configuration.要更改Bootstrap的默认Popper配置,请参阅Popper的配置

When a function is used to create the Popper configuration, it's called with an object that contains the Bootstrap's default Popper configuration. 当一个函数用于创建Popper配置时,会使用包含Bootstrap默认Popper配置的对象调用该函数。It helps you use and merge the default with your own configuration. The function must return a configuration object for Popper.它帮助您使用默认值并将其与自己的配置合并。该函数必须返回Popper的配置对象。

Data attributes for individual tooltips单个工具提示的数据属性

Options for individual tooltips can alternatively be specified through the use of data attributes, as explained above.如上所述,也可以通过使用数据属性指定单个工具提示的选项。

Using function with popperConfig将函数与popperConfig一起使用

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

Methods方法

Asynchronous methods and transitions异步方法和转换

All API methods are asynchronous and start a transition. 所有API方法都是异步的,并开始转换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.此外,转换组件上的方法调用将被忽略

See our JavaScript documentation for more information有关更多信息,请参阅JavaScript文档.

show

Reveals an element’s tooltip. 显示元素的工具提示。Returns to the caller before the tooltip has actually been shown (i.e. before the shown.bs.tooltip event occurs). 在实际显示工具提示之前(即在shown.bs.tooltip事件发生之前)返回给调用者。This is considered a “manual” triggering of the tooltip. 这被认为是工具提示的“手动”触发。Tooltips with zero-length titles are never displayed.不显示标题长度为零的工具提示。

tooltip.show()

hide

Hides an element’s tooltip. 隐藏元素的工具提示。Returns to the caller before the tooltip has actually been hidden在实际隐藏工具提示之前返回调用方 (i.e. before the hidden.bs.tooltip event occurs). (即,在hidden.bs.tooltip事件发生之前)。This is considered a “manual” triggering of the tooltip.这被认为是工具提示的“手动”触发。

tooltip.hide()

toggle

Toggles 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). (即在shown.bs.tooltiphidden.bs.tooltip事件发生之前)。This is considered a “manual” triggering of the tooltip.这被认为是工具提示的“手动”触发。

tooltip.toggle()

dispose

Hides and destroys an element’s tooltip (Removes stored data on the DOM element). 隐藏并销毁元素的工具提示(删除DOM元素上存储的数据)。Tooltips that use delegation (which are created using the selector option) cannot be individually destroyed on descendant trigger elements.使用委托(使用selector选项创建)的工具提示不能在后代触发器元素上单独销毁。

tooltip.dispose()

enable

Gives an element’s tooltip the ability to be shown. 提供显示元素的工具提示。Tooltips are enabled by default.默认情况下启用工具提示。

tooltip.enable()

disable

Removes the ability for an element’s tooltip to be shown. 删除显示元素工具提示的功能。The tooltip will only be able to be shown if it is re-enabled.工具提示只有在重新启用时才能显示。

tooltip.disable()

toggleEnabled

Toggles the ability for an element’s tooltip to be shown or hidden.切换显示或隐藏元素工具提示的功能。

tooltip.toggleEnabled()

update

Updates the position of an element’s tooltip.更新元素工具提示的位置。

tooltip.update()

getInstance

Static method which allows you to get the tooltip instance associated with a DOM element静态方法,允许您获取与DOM元素关联的工具提示实例

var exampleTriggerEl = document.getElementById('example')
var tooltip = bootstrap.Tooltip.getInstance(exampleTriggerEl) // Returns a Bootstrap tooltip instance

getOrCreateInstance

Static method which allows you to get the tooltip instance associated with a DOM element, or create a new one in case it wasn’t initialised静态方法,允许您获取与DOM元素关联的工具提示实例,或者在未初始化的情况下创建一个新实例

var exampleTriggerEl = document.getElementById('example')
var tooltip = bootstrap.Tooltip.getOrCreateInstance(exampleTriggerEl) // Returns a Bootstrap tooltip instance

Events事件

Event type事件类型 Description描述
show.bs.tooltip This event fires immediately when the show instance method is called.调用show实例方法时,此事件立即激发。
shown.bs.tooltip This event is fired when the tooltip has been made visible to the user (will wait for CSS transitions to complete).当工具提示对用户可见时(将等待CSS转换完成),将触发此事件。
hide.bs.tooltip This event is fired immediately when the hide instance method has been called.调用hide实例方法后立即激发此事件。
hidden.bs.tooltip This event is fired when the tooltip has finished being hidden from the user (will wait for CSS transitions to complete).当工具提示完成对用户隐藏时(将等待CSS转换完成),将触发此事件。
inserted.bs.tooltip This event is fired after the show.bs.tooltip event when the tooltip template has been added to the DOM.将工具提示模板添加到DOM后,在show.bs.tooltip事件之后激发此事件。
var myTooltipEl = document.getElementById('myTooltip')
var tooltip = new bootstrap.Tooltip(myTooltipEl)
myTooltipEl.addEventListener('hidden.bs.tooltip', function () {
// do something...
})
tooltip.hide()