Tooltip
为控件命名,或在悬停和键盘焦点时补上一句简短提示。
当指针停在控件上或键盘焦点到达时,tooltip 为控件命名,或补上一句简短提示。保持纯文本,几个词就够。
import "@ui-sdk/web/tooltip"
import { Bookmark, createElement } from "lucide"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-tooltip default-open>
<ui-tooltip-trigger>
<button aria-label="Add to library">${createElement(Bookmark, { "aria-hidden": "true" }).outerHTML}</button>
</ui-tooltip-trigger>
<ui-tooltip-content>Add to library</ui-tooltip-content>
</ui-tooltip>
`
}
export { mount }安装
npm install @ui-sdk/web @ui-sdk/core导入组件会定义它的元素。在服务器上,导入不会做任何事。
import "@ui-sdk/web/tooltip"组合
用下面的组合构建 ui-tooltip:
ui-tooltip
├── ui-tooltip-trigger
│ └── button
└── ui-tooltip-content
├── ui-tooltip-arrow
└── ui-tooltip-shortcut把触发器和它的提示包进一个 tooltip。触发器包装你自己的 <button> 或链接,所以原生按钮的一切行为都会保留。箭头和快捷键是可选的。
内容带有 tooltip 角色,并且从一开始就在页面里,只是隐藏着,所以在焦点到达之前,它就能为触发器命名或描述触发器。它会为没有自己名称的触发器命名,比如只有图标的按钮,并描述其他触发器,也就是带文本、aria-label 或 title 的那些。type="label" 或 type="description" 会覆盖这一判断。只放纯文本:tooltip 无法获得焦点,所以里面的链接或按钮也无法到达。需要交互时,请使用 Popover 或 Hover Card。
用法
导入部件并把它们组合起来:
<script type="module">
import "@ui-sdk/web/tooltip"
</script>
<ui-tooltip>
<ui-tooltip-trigger><button>Share</button></ui-tooltip-trigger>
<ui-tooltip-content>Anyone with the link can view</ui-tooltip-content>
</ui-tooltip>方向
side 选择 tooltip 打开的方向:默认是 top。空间不够时,它会翻到另一侧,并沿触发器平移以留在屏幕内。data-side 报告它最终落在哪里。
import "@ui-sdk/web/tooltip"
const sides = [
{ side: "top", label: "Top" },
{ side: "left", label: "Left" },
{ side: "right", label: "Right" },
{ side: "bottom", label: "Bottom" },
]
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="grid">
${sides
.map(
({ side, label }) => `
<ui-tooltip>
<ui-tooltip-trigger><button>${label}</button></ui-tooltip-trigger>
<ui-tooltip-content side="${side}">Add to library</ui-tooltip-content>
</ui-tooltip>
`
)
.join("")}
</div>
`
}
export { mount }添加 ui-tooltip-arrow 来指向触发器。它跟随 tooltip 最终的落点,翻转之后也是如此。
<ui-tooltip-content>
<ui-tooltip-arrow></ui-tooltip-arrow>
Add to library
</ui-tooltip-content>锚点
用 anchor 让 tooltip 贴着触发器以外的东西定位,它是一个 CSS 选择器,指向要对齐的元素。控制器的 open() 也接受元素、像 { x, y } 这样的点,或任何带 getBoundingClientRect() 的对象。这里字段里的小帮助按钮会让它的 tooltip 与整个字段对齐。
import "@ui-sdk/web/tooltip"
import "@ui-sdk/web/field"
import "@ui-sdk/web/input"
import { createElement, Info } from "lucide"
function mount(root: HTMLElement) {
const id = `webhook-url-${crypto.randomUUID()}`
root.innerHTML = `
<ui-field>
<ui-field-label>Webhook URL</ui-field-label>
<div data-slot="row" id="${id}">
<ui-input>
<input placeholder="https://" />
</ui-input>
<ui-tooltip>
<ui-tooltip-trigger>
<button aria-label="About webhooks">${createElement(Info, { "aria-hidden": "true" }).outerHTML}</button>
</ui-tooltip-trigger>
<ui-tooltip-content anchor="#${id}" side="bottom" align="start">
We send a POST request here for every new order.
</ui-tooltip-content>
</ui-tooltip>
</div>
</ui-field>
`
}
export { mount }键盘快捷键
tooltip 上的 shortcut,比如 "mod+s",提示触发器的动作绑定在什么按键上;其中 mod 在 Apple 平台上是 Command,在其他平台上是 Control。空的 ui-tooltip-shortcut 会显示当前平台的按键,⌘S 或 Ctrl+S,对屏幕阅读器隐藏,触发器则会得到 aria-keyshortcuts,让屏幕阅读器改为听到它。ui-tooltip-shortcut 可以用自己的 shortcut 显示其他按键。
tooltip 不会绑定这些按键。像示例那样,用 registerShortcut 自己注册快捷键,或使用会绑定按键的组件的 shortcut,比如 Dialog 的触发器。
import "@ui-sdk/web/tooltip"
import { registerShortcut } from "@ui-sdk/web"
import { createElement, Save } from "lucide"
import { log } from "./log"
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="row">
<ui-tooltip shortcut="mod+s">
<ui-tooltip-trigger>
<button aria-label="Save">${createElement(Save, { "aria-hidden": "true" }).outerHTML}</button>
</ui-tooltip-trigger>
<ui-tooltip-content>
Save
<ui-tooltip-shortcut></ui-tooltip-shortcut>
</ui-tooltip-content>
</ui-tooltip>
<ui-tooltip shortcut="mod+shift+e">
<ui-tooltip-trigger><button>Share</button></ui-tooltip-trigger>
<ui-tooltip-content>
Share with your team
<ui-tooltip-shortcut></ui-tooltip-shortcut>
</ui-tooltip-content>
</ui-tooltip>
</div>
`
const save = () => log(root, "Saved")
const share = () => log(root, "Shared")
const [saveButton, shareButton] = root.querySelectorAll("button")
saveButton.addEventListener("click", save)
shareButton.addEventListener("click", share)
const offSave = registerShortcut("mod+s", save)
const offShare = registerShortcut("mod+shift+e", share)
return () => {
offSave()
offShare()
}
}
export { mount }禁用的按钮
原生禁用的按钮无法接收焦点,而且有些浏览器不会给它发送指针事件,所以它的 tooltip 永远不会显示。当 tooltip 用来解释某个操作为什么不可用时,改用 aria-disabled="true",并由你自己忽略按钮的按压。按钮会留在 Tab 顺序中,屏幕阅读器会把它播报为变暗,tooltip 则说明缺了什么。按钮恢复可用后,tooltip 上的 disabled 会关掉这条说明。
import "@ui-sdk/web/tooltip"
import "@ui-sdk/web/field"
import "@ui-sdk/web/input"
import { log } from "./log"
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<ui-field>
<ui-field-label>Post title</ui-field-label>
<ui-input>
<input />
</ui-input>
</ui-field>
<ui-tooltip>
<ui-tooltip-trigger><button data-variant="solid" aria-disabled="true">Publish</button></ui-tooltip-trigger>
<ui-tooltip-content side="right">Add a title to publish</ui-tooltip-content>
</ui-tooltip>
</div>
`
const input = root.querySelector("input")!
const tooltip = root.querySelector("ui-tooltip")!
const publish = root.querySelector("button")!
const title = () => input.value.trim()
input.addEventListener("input", () => {
const blocked = !title()
if (blocked) {
publish.setAttribute("aria-disabled", "true")
} else {
publish.removeAttribute("aria-disabled")
}
tooltip.disabled = !blocked
})
publish.addEventListener("click", () => {
if (title()) {
log(root, `Published “${title()}”`)
}
})
}
export { mount }触摸
触摸屏没有悬停。轻点普通 tooltip 的触发器只会按压它,tooltip 仍然关闭,所以不要把重要内容藏在 tooltip 里。
如果某个信息按钮的唯一职责就是显示这条提示,就加上 toggleable:用手指、鼠标或键盘按压触发器可以打开和关闭 tooltip,按压打开时它的文本会被播报。外部按压或 Escape 也能关闭它。
import "@ui-sdk/web/tooltip"
import { createElement, Info } from "lucide"
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="row">
<span data-slot="label">Storage</span>
<ui-tooltip toggleable>
<ui-tooltip-trigger>
<button aria-label="About storage" data-size="sm">${createElement(Info, { "aria-hidden": "true" }).outerHTML}</button>
</ui-tooltip-trigger>
<ui-tooltip-content>Files in the trash still use storage.</ui-tooltip-content>
</ui-tooltip>
<span data-slot="hint">12.4 of 15 GB used</span>
</div>
`
}
export { mount }按压时保持打开
按压触发器会关闭 tooltip,这样它不会遮住按压带来的变化,而且在指针离开之前会保持关闭。close-on-press="false" 会让它保持打开,比如复制按钮的 tooltip 会变成 Copied。
import "@ui-sdk/web/tooltip"
import { Check, Copy, createElement } from "lucide"
const command = "npm install @ui-sdk/web"
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="row">
<code>${command}</code>
<ui-tooltip close-on-press="false">
<ui-tooltip-trigger><button></button></ui-tooltip-trigger>
<ui-tooltip-content></ui-tooltip-content>
</ui-tooltip>
</div>
`
const tooltip = root.querySelector("ui-tooltip")!
const button = root.querySelector("button")!
const content = root.querySelector("ui-tooltip-content")!
const render = (copied: boolean) => {
const label = copied ? "Copied" : "Copy"
button.setAttribute("aria-label", label)
button.replaceChildren(
createElement(copied ? Check : Copy, { "aria-hidden": "true" })
)
content.textContent = label
}
render(false)
button.addEventListener("click", () => {
navigator.clipboard?.writeText(command).catch(() => {})
render(true)
})
tooltip.addEventListener("openchangecomplete", (event) => {
if (!event.detail.value) {
render(false)
}
})
}
export { mount }被截断的文本
如果只想在文本被截断时才显示 tooltip,就在文本放得下时,于 openchange 中用 event.preventDefault() 取消这次打开。在监听器里比较 scrollWidth 和 clientWidth。tooltip 会重复这个名称,所以 type="label" 可以避免屏幕阅读器听到两遍。
import "@ui-sdk/web/tooltip"
import { createElement, File } from "lucide"
const files = [
"Quarterly report, final revised version for the board.pdf",
"Notes.txt",
"Design review recording, October 2nd.mp4",
"Budget.xlsx",
]
function mount(root: HTMLElement) {
root.innerHTML = `
<ul>
${files
.map(
(file) => `
<li>
<ui-tooltip type="label">
<ui-tooltip-trigger><button>${createElement(File, { "aria-hidden": "true" }).outerHTML}<span>${file}</span></button></ui-tooltip-trigger>
<ui-tooltip-content>${file}</ui-tooltip-content>
</ui-tooltip>
</li>`
)
.join("")}
</ul>
`
for (const tooltip of root.querySelectorAll("ui-tooltip")) {
tooltip.addEventListener("openchange", (event) => {
const name = tooltip.querySelector("span")
if (event.detail.value && name && name.scrollWidth <= name.clientWidth) {
event.preventDefault()
}
})
}
}
export { mount }受控
设置元素的 open property,并监听 openchange。每次变更都带有原因,比如 trigger-hover、trigger-focus、trigger-press、escape-key 或 outside-press。调用 event.preventDefault() 可以阻止它。要从任何地方打开 tooltip,比如分步引导中的某一步,请使用它的控制器。
import "@ui-sdk/web/tooltip"
import "@ui-sdk/web/checkbox"
import { Check, createElement } from "lucide"
import { log } from "./log"
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<div data-slot="controls">
<label data-slot="label">
<ui-checkbox>
<ui-checkbox-indicator>
${createElement(Check, { "aria-hidden": "true" }).outerHTML}
</ui-checkbox-indicator>
</ui-checkbox>
Open
</label>
</div>
<ui-tooltip>
<ui-tooltip-trigger><button>Export</button></ui-tooltip-trigger>
<ui-tooltip-content>Download as CSV</ui-tooltip-content>
</ui-tooltip>
</div>
`
const controls = root.querySelector('[data-slot="controls"]')!
const checkbox = root.querySelector("ui-checkbox")!
const tooltip = root.querySelector("ui-tooltip")!
checkbox.addEventListener("checkedchange", (event) => {
tooltip.open = event.detail.value === true
})
tooltip.addEventListener("openchange", (event) => {
const { value, reason, event: cause } = event.detail
const inControls =
cause?.target instanceof Node && controls.contains(cause.target)
if (inControls && reason !== "escape-key") {
return event.preventDefault()
}
checkbox.checked = value
log(root, `${value ? "Opened" : "Closed"} (${reason})`)
})
}
export { mount }共享
工具栏、图表或长列表可以共用一个 tooltip,而不是为每一项各渲染一个。给 tooltip 一个 id,并用 for 让每个触发器指向它,触发器就可以放在页面上的任何位置。每个触发器接收一个 payload,这里是来自 payload 属性的标签;在 payloadchange 触发时填充内容,payload 在 event.detail.value 里。UiTooltipElement<string> 为 payload 指定类型。内容在首次打开之前就在页面里,所以要处理 undefined 的 payload。
只有打开 tooltip 的那个触发器会被它描述,所以给每个触发器一个自己的名称,比如 aria-label。控制器的 open() 也接受 payload 和 anchor;在已打开的 tooltip 上,open({ payload }) 会替换 payload,就像另一个触发器接管了它。payloadchange 报告每次变更,包括指针或焦点移到另一个触发器上,这会在没有 openchange 的情况下移交打开的 tooltip。
当另一个触发器接管打开的 tooltip 时,tooltip 会移到它那里。把 left 和 top 加入内容的 transition,它就会滑过去而不是跳过去。打开时的第一次放置永远不做动画,所以它不会从某个角落飞进来。
import "@ui-sdk/web/tooltip"
import type { UiTooltipElement } from "@ui-sdk/web/tooltip"
import { Bold, createElement, Italic, Underline } from "lucide"
const formats = [
{ icon: Bold, label: "Bold" },
{ icon: Italic, label: "Italic" },
{ icon: Underline, label: "Underline" },
]
function mount(root: HTMLElement) {
const id = `formatting-${crypto.randomUUID()}`
root.innerHTML = `
<div data-slot="row" role="group" aria-label="Formatting">
${formats
.map(
(format) => `
<ui-tooltip-trigger for="${id}" payload="${format.label}">
<button aria-label="${format.label}">${createElement(format.icon, { "aria-hidden": "true" }).outerHTML}</button>
</ui-tooltip-trigger>
`
)
.join("")}
<ui-tooltip id="${id}">
<ui-tooltip-content></ui-tooltip-content>
</ui-tooltip>
</div>
`
const tooltip = root.querySelector<UiTooltipElement<string>>("ui-tooltip")!
const content = root.querySelector("ui-tooltip-content")!
tooltip.addEventListener("payloadchange", (event) => {
content.textContent = event.detail.value ?? ""
})
}
export { mount }动画
内容在打开时带有 data-starting-style,关闭时带有 data-ending-style。从这些状态做过渡,tooltip 会保持挂载,直到退场结束。把 transform-origin: var(--transform-origin) 放在内容上,让它从触发器长出来。立即打开的 tooltip,比如分组里的下一个,会得到 data-instant,所以在那里跳过过渡。
[data-slot="tooltip-content"] {
transform-origin: var(--transform-origin);
transition:
opacity 150ms ease-out,
scale 150ms ease-out;
&:is([data-starting-style], [data-ending-style]) {
opacity: 0;
scale: 0.9;
}
&[data-instant] {
transition: none;
}
}对于要求减少动态效果的人,在 prefers-reduced-motion 查询里去掉缩放,保留淡入淡出。openchangecomplete 在 tooltip 完成打开或关闭后触发,位于任何动画之后,新的打开状态在 event.detail.value 里。
import "@ui-sdk/web/tooltip"
import { Archive, createElement } from "lucide"
import { log } from "./log"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-tooltip>
<ui-tooltip-trigger>
<button aria-label="Archive">${createElement(Archive, { "aria-hidden": "true" }).outerHTML}</button>
</ui-tooltip-trigger>
<ui-tooltip-content>Archive</ui-tooltip-content>
</ui-tooltip>
`
const tooltip = root.querySelector("ui-tooltip")!
tooltip.addEventListener("openchange", (event) =>
log(root, event.detail.value ? "Opening" : "Closing")
)
tooltip.addEventListener("openchangecomplete", (event) =>
log(root, event.detail.value ? "Open" : "Closed")
)
}
export { mount }延迟与分组
delay 是指针在触发器上停驻多久之后 tooltip 打开,默认 600 毫秒。close-delay 是指针离开触发器和 tooltip 之后它还会停留多久,默认 0。键盘焦点会立即打开它。
tooltip 不需要 provider 就能分组。一旦有一个打开,或者刚刚打开过,悬停下一个就会立即打开它,而且同一时间只有一个打开,所以沿工具栏移动读起来就像一个 tooltip 跟着指针走。立即打开的 tooltip 会得到 data-instant,因此可以跳过动画。
disabled 会阻止 tooltip 打开,同时触发器继续正常工作。
<ui-tooltip delay="300" close-delay="150" disabled></ui-tooltip>偏移
side-offset 是与触发器之间的间距,默认 4 像素。align-offset 沿它平移,align 让它与触发器的 start、center 或 end 对齐,collision-padding 是离窗口边缘保留的空间。
<ui-tooltip-content
align="start"
side-offset="8"
align-offset="4"
collision-padding="16"
></ui-tooltip-content>容器
tooltip 就地渲染并显示在顶层,所以不会被任何祖先元素裁剪或遮挡。container 是一个 CSS 选择器,把 tooltip 渲染到别处,适用于 iframe、影子根(shadow root)或特定的层叠上下文。见共享的浮层指南。
<ui-tooltip-content container="#tooltips"></ui-tooltip-content>自定义渲染
元素没有渲染函数。触发器包装你自己的元素,一个按钮或链接,那个元素就是触发器,带你的属性。从每个部件设置的数据属性读取状态。渲染约定见部件与组合。
import "@ui-sdk/web/tooltip"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-tooltip>
<ui-tooltip-trigger><a href="https://example.com/changelog" data-variant="link">Changelog</a></ui-tooltip-trigger>
<ui-tooltip-content>See what's new in 2.0</ui-tooltip-content>
</ui-tooltip>
`
}
export { mount }一个按钮可以同时是 tooltip 的触发器和另一个组件的触发器。把触发器嵌套起来,两者都会绑定最里面的按钮,所以它会打开 popover,并由 tooltip 命名:
<ui-popover>
<ui-tooltip>
<ui-tooltip-trigger>
<ui-popover-trigger>
<button><svg aria-hidden="true">…</svg></button>
</ui-popover-trigger>
</ui-tooltip-trigger>
<ui-tooltip-content>Notifications</ui-tooltip-content>
</ui-tooltip>
<ui-popover-content>...</ui-popover-content>
</ui-popover>样式
用 data-side 和 data-align 为内容和箭头按最终落点设置样式,用 data-instant 跳过立即打开的 tooltip 的动画。触发器没有自己的状态属性,因为它常常也是另一个组件的触发器,比如菜单的触发器。把 transform-origin: var(--transform-origin) 放在内容上,让它从触发器开始缩放。
每个部件都有一个 data-slot,比如 tooltip-content,它的状态属性列在数据属性下。
<ui-tooltip-content>
| 变量 | 内容 |
|---|---|
--anchor-width | Width of the anchor, usually the trigger. Use it to match widths. |
--anchor-height | Height of the anchor. |
--available-width | Space beside the popup, up to the viewport edge. Not inherited either. |
--available-height | Space between the anchor and the viewport edge. Use it for max-height. Not inherited, so a child that needs it copies it on the popup, like [--list-height:var(--available-height)], and reads max-h-(--list-height). The first popup registers both names for the whole page with CSS.registerProperty, so they don't inherit anywhere. A page that needs them to inherit calls it first, with inherits: true. An @property rule can't, since a registration in script wins. |
--transform-origin | The point on the anchor the popup opens from. Use it to scale from the right place. |
--arrow-offset | Where the anchor's center falls along the popup's edge, kept arrowPadding from the corners. Position a ::before arrow with it. |
数据属性
<ui-tooltip-trigger> 和 <ui-tooltip-shortcut> 没有状态属性。
<ui-tooltip-content>
[data-slot="tooltip-content"]
| 属性 | 含义 |
|---|---|
data-closed | Present while the tooltip is closed, including while it animates out. |
data-open | Present while the tooltip is open. |
data-starting-style | Present for the first frame. Style the state you animate from. |
data-ending-style | Present while the tooltip animates out. Style the state you animate to. |
data-side | toprightbottomleftWhere the tooltip ended up, after flipping away from edges. Set on the arrow too. |
data-align | startcenterendHow the tooltip lines up with its trigger. |
<ui-tooltip-arrow>
[data-slot="tooltip-arrow"]
| 属性 | 含义 |
|---|---|
data-closed | Present while the tooltip is closed, including while it animates out. |
data-open | Present while the tooltip is open. |
data-side | toprightbottomleftWhere the tooltip ended up, after flipping away from edges. Set on the arrow too. |
data-align | startcenterendHow the tooltip lines up with its trigger. |
data-arrow-clamped | Present on the arrow when it stops short of the middle of the trigger, held back by arrowPadding. |
API 参考
属性是 kebab 写法的 attribute,比如 close-delay 和 side-offset:"false" 表示 false,数字仍然是数字。anchor 和 container 接受 CSS 选择器。回调是 DOM 事件。
Tooltip
container?DocumentFragment | Element | null- Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
open?boolean- Whether the tooltip is open. Pass it to control the tooltip.
defaultOpen?boolean- Whether the tooltip starts open, when uncontrolled.
openchange event- Runs when the tooltip wants to open or close.
details.reasonsays why, anddetails.cancel()stops it. openchangecomplete event- Runs once the tooltip has finished opening or closing, after any animation.
payloadchange event- Runs when the payload the content shows changes: a trigger with another payload opens the tooltip, or takes the open tooltip over, which fires no
openchange, and so does a controller'sopen({ payload })on the open tooltip.details.cancel()keeps the previous payload. delay?number- Milliseconds the pointer rests on the trigger before the tooltip opens. While another tooltip is open, or was a moment ago, the next one opens at once, without a provider.
closeDelay?number- Milliseconds before the tooltip closes once the pointer leaves the trigger and the tooltip.
disabled?boolean- Stops the tooltip from opening. The trigger keeps working.
toggleable?boolean- Whether pressing the trigger opens and closes the tooltip, so touch screens can show it too. For info buttons whose only job is the tip. The text is announced when a press opens it.
closeOnPress?boolean- Whether pressing the trigger closes the tooltip. Set it to
falseto keep it open, like for a copy button whose tooltip turns into "Copied". type?"description" | "label"- Whether the tooltip names its trigger (
"label") or adds a description to it ("description"). By default it names a trigger that has no name of its own, like an icon button, and describes any other. shortcut?string- The keyboard shortcut of what the trigger does, like
"mod+s", as a hint. ATooltipShortcutshows it, and the trigger getsaria-keyshortcuts. It doesn't bind the keys: the trigger's ownshortcut, orregisterShortcut, does. controller?PopupController<any, TooltipOpenChangeReason, {}, string, TooltipPayloadChangeReason>- Opens, closes and inspects the tooltip from anywhere, and connects triggers outside it. Create one with
createTooltipController(). debug?boolean- Logs every state change with its reason to the console, in development builds.
TooltipTrigger
tooltip 之外的触发器用 for="tooltip-id" 为它命名,并用 payload property 传入数据,或用 payload attribute 字符串。两者都有时 property 优先。
payload?unknown- Data for the content to render when this trigger opens the tooltip, like the row it belongs to.
controller?PopupController<any, TooltipOpenChangeReason, {}, string, TooltipPayloadChangeReason>- Connects a trigger outside the tooltip, like one per table row, to the tooltip with this controller.
TooltipContent
side?Side- Which side of the anchor the popup opens on. Flips to the other side when there isn't room. Which side of the trigger the tooltip opens on.
align?Align- How the popup lines up with the anchor along that side.
startandendfollow the reading direction. How the tooltip lines up with the trigger along that side. sideOffset?number- Gap between the anchor and the popup, in pixels. Gap between the trigger and the tooltip, in pixels.
alignOffset?number- Shift along the anchor, in pixels. Shift along the trigger, in pixels.
collisionPadding?number- Space to keep from the viewport edges, in pixels.
arrowPadding?number- Space to keep between the arrow and the popup's corners, in pixels.
anchor?string | Anchor | null- Positions the popup against this instead of its trigger: an element, a CSS selector, a point like
{ x, y }, or anything withgetBoundingClientRect(). It's read on every check, so it can move. A controller'sopen({ anchor })wins for that open. container?DocumentFragment | Element | null- Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
TooltipArrow
从 tooltip 最终所在的一侧指向触发器。
TooltipShortcut
shortcut?string- The keys to show. By default, the tooltip's
shortcut.
状态
同样的状态会作为数据属性显示在每个元素上。
TooltipTrigger:
openboolean- Whether the tooltip is open from this trigger.
TooltipContent:
openboolean- Whether the tooltip is open. False while it animates out.
instantboolean- Whether it opened at once, because another tooltip was open a moment ago. Animations can skip.
payloadPayload | undefined- The payload of the last open, from the trigger that opened it or a controller, typed as the controller's
Payload.
TooltipArrow:
openboolean- Whether the tooltip is open. False as soon as it starts closing, while it still animates out.
TooltipShortcut:
textstring- The shortcut formatted for this platform:
⌘Son Apple platforms andCtrl+Selsewhere. Empty without one.
原因
event.detail.reason 说明 tooltip 为什么打开或关闭。
trigger-hoverPointerEvent- The pointer rested on a trigger, or left it, with hover opening.
trigger-focusFocusEvent- Keyboard focus reached a trigger that opens on focus, like a tooltip's.
trigger-pressMouseEvent | KeyboardEvent | TouchEvent- Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its
touchend. focus-outKeyboardEvent | FocusEvent- Focus left the layer, or Tab moved it out.
escape-keyKeyboardEvent- Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
close-pressMouseEvent | KeyboardEvent | SubmitEvent- A Close part was pressed, or a form with
method="dialog"was submitted. outside-pressMouseEvent- A press outside the layer.
window-blurFocusEvent- The window lost focus.
backEvent- Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
anchor-hiddennone- The element the popup sits beside stopped rendering, like a trigger a breakpoint hides.
imperativenone- A controller or
apicall.
payload 变更时,它说明是什么打开了 tooltip 或接管了它。
trigger-hoverPointerEvent- The pointer rested on a trigger, or left it, with hover opening.
trigger-focusFocusEvent- Keyboard focus reached a trigger that opens on focus, like a tooltip's.
trigger-pressMouseEvent | KeyboardEvent | TouchEvent- Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its
touchend. imperativenone- A controller or
apicall.
控制器
元素的 api property 拥有相同的方法。open property 读取并设置 tooltip 是否打开。
每个写入方法都接受一个可选的 { reason, event },传给 openchange。
isOpen()() => boolean- Whether it's open. False as soon as it starts closing, while it still animates out.
setOpen(open, options?)(open: boolean, options?: PopupChangeOptions<TooltipOpenChangeReason> | undefined) => boolean- Opens or closes it. Returns false when the change was canceled or it was already open or closed.
open(options?)(options?: (PopupChangeOptions<TooltipPayloadChangeReason> & { payload?: Payload | undefined; anchor?: Anchor | undefined; signal?: AbortSignal | undefined; }) | undefined) => Promise<...>- Opens it, and resolves once it closes, with why, how and any return value. Resolves exactly once and never rejects: on the next close from any source, when
signalaborts, or with reason"unmount"when the component leaves the page. close(options?)(options?: (PopupChangeOptions<TooltipOpenChangeReason> & { returnValue?: string | undefined; }) | undefined) => boolean- Closes it.
returnValueis passed to the promiseopen()returned. Returns false when the close was canceled or it was already closed. toggle(options?)(options?: PopupChangeOptions<TooltipOpenChangeReason> | undefined) => boolean- Opens it when it's closed, and closes it when it's open. Returns false when the change was canceled.
getPayload()() => Payload | undefined- The payload of the last open, from a controller or the trigger that opened it.
focus()() => void- Moves focus to the trigger that opened it last, or the first trigger.
事件
事件在自己的元素上触发,不冒泡,新状态在 event.detail.value 中,reason 和 event 在它旁边。在 openchange 上调用 preventDefault() 可以取消这次变更。
| 成员 | 所属 | 说明 |
|---|---|---|
open property, 属性 | ui-tooltip | tooltip 是否打开。属性设置它的起始值,并且是实时的 |
api property | ui-tooltip | 控制器 |
openchange 事件 | ui-tooltip | detail: { value: open, reason, event } |
openchangecomplete 事件 | ui-tooltip | detail: { value: open },在动画之后 |
payloadchange 事件 | ui-tooltip | detail: { value: payload, reason, event },在内容的 payload 变更时 |
payload property | ui-tooltip-trigger | 给内容的数据 |
for 属性 | ui-tooltip-trigger | 触发器从外部打开的 tooltip 的 id |
无障碍
触发器由 tooltip 命名或描述,遵循 WAI-ARIA tooltip 模式。它在悬停和键盘焦点时打开,并在指针移入它时保持打开。
键盘
| 按键 | 作用 |
|---|---|
| Tab | 焦点落在触发器上会立即打开 tooltip;焦点离开它会关闭 tooltip |
| Escape | 关闭 tooltip,并把焦点留在触发器上,不会关闭它周围的对话框或菜单 |
| Enter, Space | 按压触发器并关闭 tooltip;在 toggleable 触发器上,打开和关闭它 |
经过测试的行为
下面每一行都是一个自动化测试。
- Resting the pointer on the trigger opens the tooltip.
- The tooltip waits for its delay before opening.
- Leaving the trigger before the delay keeps the tooltip closed.
- Moving the pointer away closes the tooltip.
- The pointer can move onto the tooltip without closing it.
- Opening on hover leaves focus where it was.
- Pressing the trigger closes the tooltip and runs the button.
- After a press, the tooltip stays closed until the pointer comes back.
- Keyboard focus on the trigger opens the tooltip.
- Focus leaving the trigger closes the tooltip.
- Escape closes the tooltip and leaves focus on the trigger.
- Escape closes a tooltip opened by hover.
- Tab through the toolbar shows each tooltip in turn.
- A click that focuses the trigger doesn't open the tooltip from focus.
- Only one tooltip is open at a time.
- Once the pointer has been away a while, the delay applies again.
- The tooltip opens above the trigger.
- The tooltip flips below the trigger when there is no room above.
- The tooltip opens on the requested side.
- The arrow points at the middle of the trigger.
- Hovering shows the tooltip, and pressing opens the popover instead.
- Escape closes the tooltip and leaves the popover open.
- Browsers send hover events to a disabled button.
- An aria-disabled trigger shows its tooltip on hover and focus and ignores presses.
- The tooltip animates in from its starting style.
- The tooltip stays in the page while it animates out.
- A class that sets display on the content doesn't show it while closed.
- Escape closes only a tooltip that keyboard focus opened inside a popover.
- The pointer can leave the trigger sideways on its way to the tooltip.
- With closeOnPress false, pressing the trigger keeps the tooltip open.
- Disabled tooltips never open.
- A tap on a plain tooltip's trigger only presses it.
运行于 React、Vue 和 web components。
其他行为:
- Focus returning to the trigger after its popover closes doesn't reopen the tooltip.
- Tooltips open at once after another one, without a provider.
- Focus coming back with the window doesn't reopen the tooltip.
- A controller opens the tooltip without moving focus.
- A trigger that's a disabled button warns in development.
- A trigger connected through a controller shows its tooltip's shortcut in a Shortcut part.
- Pressing a toggleable trigger opens and closes the tooltip.
- Pressing outside closes a toggleable tooltip.
- Enter toggles the tooltip from the keyboard and keeps focus on the trigger.
- A press announces the tooltip's text to screen readers.
- A tap opens a toggleable tooltip on a touch screen.
运行于 React、Vue 和 web components。
在每个经过测试的框架里,屏幕阅读器听到的内容相同,由虚拟屏幕阅读器记录:
- Announcements while tabbing through triggers with tooltips.
运行于 React、Vue 和 web components。