Tooltip文字提示
Tooltip 是元素的简短文字提示:用来解释按钮、图标或一段文字。悬停和键盘聚焦时显示,且永远不会抢占焦点。
何时使用
- 用提示来解释按钮、图标或一小段文字。它常用来代替原生的
title属性。 - 提示用于简短说明。不要在其中放链接、按钮等控件:焦点离开触发元素时提示就会关闭,键盘无法使用它们。这类内容应使用 popover(库中暂未提供)。
- 指针或焦点离开后提示会再次隐藏,所以用户必需的信息应放在页面本身。
代码演示
Plain text with tabindex
<script lang="ts">
import { Button, Tooltip } from 'svelte-ant-design';
</script>
<!-- The child is one element. Hover it, or press Tab to focus it: both show the tip. -->
<Tooltip title="prompt text">
<Button>Tooltip will show on hover and on focus</Button>
</Tooltip>
<!-- A plain element can be hovered; give it tabindex="0" so that the keyboard can reach it too. -->
<Tooltip title="prompt text">
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<span class="plain" tabindex="0">Plain text with tabindex</span>
</Tooltip>
<style>
.plain {
margin-inline-start: 16px;
text-decoration: underline dotted;
cursor: help;
}
</style>
<script lang="ts">
import { Button, Tooltip, type TooltipPlacement } from 'svelte-ant-design';
// The buttons stand in a ring, and the middle is empty: a tip that points to the left or to the right then has free
// space beside it instead of covering the next button. The label is short; the tip says the full name.
const top: Array<[TooltipPlacement, string]> = [['topLeft', 'TL'], ['top', 'Top'], ['topRight', 'TR']];
const left: Array<[TooltipPlacement, string]> = [['leftTop', 'LT'], ['left', 'Left'], ['leftBottom', 'LB']];
const right: Array<[TooltipPlacement, string]> = [['rightTop', 'RT'], ['right', 'Right'], ['rightBottom', 'RB']];
const bottom: Array<[TooltipPlacement, string]> = [['bottomLeft', 'BL'], ['bottom', 'Bottom'], ['bottomRight', 'BR']];
</script>
{#snippet side(items: Array<[TooltipPlacement, string]>)}
{#each items as [placement, label] (placement)}
<Tooltip title={placement} {placement}>
<Button>{label}</Button>
</Tooltip>
{/each}
{/snippet}
<div class="ring">
<div class="top">{@render side(top)}</div>
<div class="left">{@render side(left)}</div>
<div class="right">{@render side(right)}</div>
<div class="bottom">{@render side(bottom)}</div>
</div>
<style>
/* A ring: a row on top, a column on each side, a row at the bottom. It shrinks with the screen, so the page does not
scroll sideways on a phone. */
.ring {
display: grid;
grid-template-columns: max-content minmax(0, 1fr) max-content;
grid-template-areas:
'. top .'
'left . right'
'. bottom .';
gap: 12px;
width: min(100%, 420px);
margin-inline: auto;
padding: 40px 0;
}
.top,
.bottom {
display: flex;
justify-content: center;
gap: 8px;
}
.left,
.right {
display: flex;
flex-direction: column;
gap: 8px;
}
.left {
align-items: flex-start;
}
.right {
align-items: flex-end;
}
.top {
grid-area: top;
}
.left {
grid-area: left;
}
.right {
grid-area: right;
}
.bottom {
grid-area: bottom;
}
</style>
<script lang="ts">
import { Button, Tooltip } from 'svelte-ant-design';
</script>
<!-- Shown by default. -->
<Tooltip title="prompt text" placement="topLeft">
<Button>Arrow at the edge</Button>
</Tooltip>
<!-- pointAtCenter points the arrow at the middle of a short trigger, wherever the tip is aligned. -->
<Tooltip title="prompt text" placement="topLeft" arrow={{ pointAtCenter: true }}>
<Button>pointAtCenter</Button>
</Tooltip>
<Tooltip title="prompt text" arrow={false}>
<Button>No arrow</Button>
</Tooltip>
<script lang="ts">
import { Button, Tooltip } from 'svelte-ant-design';
</script>
<!-- The default is hover and focus. A single value or an array. -->
<Tooltip title="hover" trigger="hover">
<Button>hover</Button>
</Tooltip>
<Tooltip title="focus: it opens when the field gets focus" trigger="focus">
<input class="field" aria-label="Focus to see the tip" placeholder="focus" />
</Tooltip>
<Tooltip title="click: press again, press elsewhere or Escape to close it" trigger="click">
<Button>click</Button>
</Tooltip>
<Tooltip title="contextMenu: the browser menu is suppressed" trigger="contextMenu">
<Button>right click</Button>
</Tooltip>
<Tooltip title="hover or click" trigger={['hover', 'click']}>
<Button>hover or click</Button>
</Tooltip>
<!-- An empty array: no trigger at all, only the open prop opens it (see Control). -->
<style>
.field {
height: 32px;
padding: 0 11px;
border: 1px solid var(--ads-color-border);
border-radius: 6px;
background: var(--ads-color-bg-container);
color: var(--ads-color-text);
font: inherit;
}
</style>
<script lang="ts">
import { Button, Tooltip } from 'svelte-ant-design';
</script>
<!-- Both delays are in seconds and default to 0.1. The pointer may cross into the tip and rest in it. -->
<Tooltip title="shown after 0.8 s" mouseEnterDelay={0.8}>
<Button>mouseEnterDelay 0.8</Button>
</Tooltip>
<Tooltip title="stays 1.5 s after you leave; move into it to keep it" mouseLeaveDelay={1.5}>
<Button>mouseLeaveDelay 1.5</Button>
</Tooltip>
<Tooltip title="instant" mouseEnterDelay={0} mouseLeaveDelay={0}>
<Button>no delay</Button>
</Tooltip>
no change yet
<script lang="ts">
import { Button, Tooltip } from 'svelte-ant-design';
let open = $state(false);
let log = $state('no change yet');
let host = $state<HTMLElement>();
</script>
<!-- bind:open keeps the parent in step; onopenchange runs once per change the user causes. -->
<Tooltip bind:open title="Controlled tooltip" onopenchange={(next) => (log = `onopenchange(${next})`)}>
<Button>Hover or focus me</Button>
</Tooltip>
<Button onclick={() => (open = !open)}>{open ? 'Hide' : 'Show'} from the parent</Button>
<span role="status">{log}</span>
<!-- An empty trigger list and open: only the parent decides. container keeps a tip that is always there inside the
region of the page, so that it is not a loose block outside every landmark. -->
<div class="always" bind:this={host}>
<Tooltip open title="Always open" trigger={[]} placement="right" container={host}>
<Button>No triggers</Button>
</Tooltip>
</div>
<style>
.always {
position: relative;
display: inline-block;
margin-inline-start: 12px;
}
</style>
<script lang="ts">
import { Button, Tooltip, TOOLTIP_PRESET_COLORS } from 'svelte-ant-design';
const custom = ['#f50', '#2db7f5', '#87d068', '#108ee9', 'hsl(280 60% 25%)'];
</script>
<!-- A name from the palette is a preset. The text is black or white, whichever contrasts more. -->
{#each TOOLTIP_PRESET_COLORS as color (color)}
<Tooltip title="{color} tip" {color}>
<Button>{color}</Button>
</Tooltip>
{/each}
<span class="break"></span>
<!-- Any other string is a CSS color. The arrow follows it, and so does the text color. -->
{#each custom as color (color)}
<Tooltip title="{color} tip" {color}>
<Button>{color}</Button>
</Tooltip>
{/each}
<style>
/* The preview is a wrapping row: this empty element is a line break in it. */
.break {
flex-basis: 100%;
height: 0;
}
</style>
<script lang="ts">
import { Button, Tooltip } from 'svelte-ant-design';
</script>
{#snippet rich()}
<strong>Bold</strong> and <em>italic</em>, a snippet can hold markup (but not links or buttons: use a popover for those).
{/snippet}
<!-- A string is text, never HTML. -->
<Tooltip title="<b>text</b>, not markup">
<Button>String</Button>
</Tooltip>
<!-- A snippet is the content. -->
<Tooltip title={rich}>
<Button>Snippet</Button>
</Tooltip>
<!-- A number is shown, and 0 too. -->
<Tooltip title={0}>
<Button>Number</Button>
</Tooltip>
<!-- The text wraps at 250 px, and a long word breaks. -->
<Tooltip title="A longer text wraps at a maximum width of 250 pixels, and Supercalifragilisticexpialidocious-is-a-word-that-breaks.">
<Button>Long text</Button>
</Tooltip>
<script lang="ts">
import { Button, Tooltip } from 'svelte-ant-design';
let title = $state('A tip');
</script>
<!-- An empty title (undefined, null or '') means no tooltip: it never opens, even with open. -->
<Tooltip {title}>
<Button>{title ? 'Has a tip' : 'No tip'}</Button>
</Tooltip>
<Button onclick={() => (title = title ? '' : 'A tip')}>Empty the title</Button>
<!-- A disabled button shows its tip (checked in Chromium, Firefox and WebKit, current and at the lowest versions). -->
<Tooltip title="Why it is disabled">
<Button disabled>Disabled</Button>
</Tooltip>
<!-- For a control that swallows pointer events by itself, a span around it is the safe form. -->
<Tooltip title="Why it is disabled">
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<span class="wrap" tabindex="0"><Button disabled>Disabled in a span</Button></span>
</Tooltip>
<style>
.wrap {
display: inline-block;
}
</style>
<script lang="ts">
import { Button, Tooltip } from 'svelte-ant-design';
let host = $state<HTMLElement>();
let visible = $state(false);
</script>
<!-- autoAdjustOverflow flips the tip to the other side when there is no room (this trigger is at the left edge). -->
<div class="edge">
<Tooltip title="flips to the right" placement="left">
<Button>Flips</Button>
</Tooltip>
<Tooltip title="stays on the left, and runs off the screen" placement="left" autoAdjustOverflow={false}>
<Button>autoAdjustOverflow off</Button>
</Tooltip>
</div>
<!-- zIndex overrides the tooltip layer (1070 by default). -->
<Tooltip title="zIndex 3000" zIndex={3000}>
<Button>zIndex</Button>
</Tooltip>
<!-- container moves the tip into an element; the tip is clipped by it. -->
<div class="host" bind:this={host}>
<Tooltip title="Inside the box" container={host}>
<Button>container</Button>
</Tooltip>
</div>
<!-- destroyOnHidden removes the content from the DOM on every close; the text below is its state. -->
<Tooltip title="Removed when closed" destroyOnHidden onopenchange={(next) => (visible = next)}>
<Button>destroyOnHidden</Button>
</Tooltip>
<span role="status">{visible ? 'in the DOM' : 'removed'}</span>
<style>
.edge {
display: flex;
gap: 12px;
margin-bottom: 12px;
}
.host {
position: relative;
display: inline-block;
padding: 28px 12px 4px;
margin: 0 12px;
border: 1px dashed #8c8c8c;
}
</style>
<script lang="ts">
import { Button, Tooltip } from 'svelte-ant-design';
</script>
<!-- root: the positioned element, container: the visible box, arrow: the little square pointing at the trigger. -->
<Tooltip
title="With classes"
classNames={{ root: 'tt-demo-root', container: 'tt-demo-box', arrow: 'tt-demo-arrow' }}
>
<Button>classNames</Button>
</Tooltip>
<!-- styles are inline styles per part; custom properties work too. -->
<Tooltip
title="With styles"
styles={{
container: { 'font-weight': 700, 'letter-spacing': '0.02em', '--ads-tooltip-bg': '#237804' },
arrow: { opacity: 0.9 }
}}
>
<Button>styles</Button>
</Tooltip>
<style>
:global(.tt-demo-root) {
filter: drop-shadow(0 4px 8px rgb(0 0 0 / 35%));
}
:global(.tt-demo-box) {
outline: 2px solid #faad14;
outline-offset: 1px;
}
:global(.tt-demo-arrow) {
outline: 2px solid #faad14;
}
</style>
<script lang="ts">
import { Button, Checkbox, Switch, Tooltip } from 'svelte-ant-design';
let target = $state<HTMLElement | null>(null);
let on = $state(false);
</script>
<Tooltip title="Saves the draft">
<Button type="primary">Save</Button>
</Tooltip>
<Tooltip title="Turns the alerts on or off">
<Switch aria-label="Alerts" />
</Tooltip>
<!-- The whole label is the trigger: moving from the box to its text does not close the tip. -->
<Tooltip title="You can change this later">
<Checkbox>Agree with the terms</Checkbox>
</Tooltip>
<!-- An icon-only button needs a name of its own: a tooltip describes, it does not name. -->
<Tooltip title="Add to favorites">
<Button shape="circle" aria-label="Add to favorites">+</Button>
</Tooltip>
<!-- anchor places the tip at an element that you hold, with no wrapper around it. -->
<button type="button" class="native" bind:this={target} onclick={() => (on = !on)}>Anchor: click me</button>
<Tooltip title="Placed at the button on the left" anchor={target} open={on} trigger={[]} placement="bottom" />
<style>
.native {
height: 32px;
padding: 0 15px;
border: 1px solid var(--ads-color-border);
border-radius: 6px;
background: var(--ads-color-bg-container);
color: var(--ads-color-text);
font: inherit;
cursor: pointer;
}
</style>
API
| 属性 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| title | 提示的文字或内容:字符串(始终作为文本,不解析 HTML)、数字或 snippet。为空(未提供、null、'')表示没有提示:即使 open 为 true 也不会打开。0 会显示。 | string | number | Snippet | null | — |
| children | 触发元素:一个元素。提示显示在它旁边,并监听它的悬停、聚焦、点击与右键菜单。组件会在外面加一个没有自身盒子的元素(display: contents),因此不会改变布局。纯文本不能作为触发元素。 | Snippet | — |
| open | 提示是否显示。使用 bind:open 双向绑定;直接传值则作为初始状态。 | boolean | false |
| onopenchange | 用户引起的每次变化(触发、Escape、点击外部)时调用一次,参数为新的值。父组件修改 open 时不会调用。 | (open: boolean) => void | — |
| placement | 首选位置:触发元素的一侧加对齐方式。在从右到左的布局中镜像,在屏幕边缘翻转。 | 'top' | 'topLeft' | 'topRight' | 'bottom' | 'bottomLeft' | 'bottomRight' | 'left' | 'leftTop' | 'leftBottom' | 'right' | 'rightTop' | 'rightBottom' | 'top' |
| trigger | 触发提示的方式:单个值或数组。空数组表示仅受控。默认包含 focus,使键盘用户也能看到提示;React 版 Ant Design 默认是 hover。 | 'hover' | 'focus' | 'click' | 'contextMenu' | readonly ('hover' | 'focus' | 'click' | 'contextMenu')[] | ['hover', 'focus'] |
| mouseEnterDelay | 悬停后显示提示前的延迟,单位为秒。 | number | 0.1 |
| mouseLeaveDelay | 鼠标离开后隐藏提示前的延迟,单位为秒。指针可以移入提示并停留。 | number | 0.1 |
| arrow | 显示箭头。{ pointAtCenter: true } 让箭头指向触发元素的中心,而不是对齐的边缘。 | boolean | { pointAtCenter: boolean } | true |
| autoAdjustOverflow | 空间不足时翻转到对侧,对未对齐的位置沿边缘平移。 | boolean | true |
| color | 背景色:13 个预设名之一(pink、red、yellow、orange、cyan、green、blue、purple、geekblue、magenta、volcano、gold、lime)或任意 CSS 颜色。列表中的名字是预设,若要 CSS 的蓝色请写 #0000ff。文字取黑或白中对比度更高者。浏览器无法解析的颜色会保留默认样式。 | string | — |
| zIndex | 覆盖提示层的 z-index(--ads-tooltip-z-index,1070)。 | number | — |
| container | 提示被放入的位置:一个元素,或接收触发元素并返回元素的函数。默认 document.body。当提示需要位于局部主题或会裁剪内容的容器内时使用。 | HTMLElement | ((anchor: HTMLElement | null) => HTMLElement) | — |
| destroyOnHidden | 每次关闭时从 DOM 中移除内容。默认在首次打开后保持挂载。 | boolean | false |
| classNames | 为 root(定位元素)、container(可见的框)与 arrow 三个部分追加的类名,附加在组件自带类名之后。 | Partial<Record<'root' | 'container' | 'arrow', string>> | — |
| styles | 这些部分的内联样式。属性名使用 kebab-case 或自定义属性,数字原样输出(不会自动添加 px)。在 root 上逐个属性设置,因此不会破坏定位。 | Partial<Record<'root' | 'container' | 'arrow', Record<string, string | number>>> | — |
| anchor | 提示所放置的元素,用来代替 children 的第一个元素。可在没有子元素时使用,或把提示放到另一个元素旁。 | HTMLElement | null | — |
与 Ant Design 的差异:触发方式默认是悬停加聚焦(React 仅悬停);13 个预设颜色按对比度使用黑或白文字,而 Ant Design 使用白字;没有
defaultOpen(请用 bind:open)、fresh、forceAlign 与 align;classNames 与 styles 是对象而非函数;ConfigProvider 的设置与 tooltip.unique 将随 ConfigProvider 组件一起提供;子元素外会包一层没有自身盒子的元素,anchor 对应 Angular 的 nzTooltipOrigin。设计令牌
| 令牌 | 说明 | 默认值 |
|---|---|---|
| --ads-tooltip-bg | 提示框的背景色。深色主题为 #424242。箭头同样使用它。 | #262626 |
| --ads-tooltip-color | 默认提示框的文字颜色。 | #ffffff |
| --ads-tooltip-radius | 提示框圆角(不超过 8px)。 | 6px |
| --ads-tooltip-padding | 提示框内边距。 | 6px 8px |
| --ads-tooltip-min-height | 提示框最小高度。 | 32px |
| --ads-tooltip-max-width | 提示框最大宽度;更长的文字会换行。 | 250px |
| --ads-tooltip-z-index | 提示层的层级,高于 popover(1030)以及 dropdown 与 select(1050)。 | 1070 |
| --ads-tooltip-preset-pink | 预设 pink 在浅色主题下的背景色;深色主题有自己的取值。--ads-tooltip-preset-pink-text 是它的文字颜色。 | #eb2f96 |
| --ads-tooltip-preset-red | 预设 red 在浅色主题下的背景色;深色主题有自己的取值。--ads-tooltip-preset-red-text 是它的文字颜色。 | #f5222d |
| --ads-tooltip-preset-yellow | 预设 yellow 在浅色主题下的背景色;深色主题有自己的取值。--ads-tooltip-preset-yellow-text 是它的文字颜色。 | #fadb14 |
| --ads-tooltip-preset-orange | 预设 orange 在浅色主题下的背景色;深色主题有自己的取值。--ads-tooltip-preset-orange-text 是它的文字颜色。 | #fa8c16 |
| --ads-tooltip-preset-cyan | 预设 cyan 在浅色主题下的背景色;深色主题有自己的取值。--ads-tooltip-preset-cyan-text 是它的文字颜色。 | #13c2c2 |
| --ads-tooltip-preset-green | 预设 green 在浅色主题下的背景色;深色主题有自己的取值。--ads-tooltip-preset-green-text 是它的文字颜色。 | #52c41a |
| --ads-tooltip-preset-blue | 预设 blue 在浅色主题下的背景色;深色主题有自己的取值。--ads-tooltip-preset-blue-text 是它的文字颜色。 | #1677ff |
| --ads-tooltip-preset-purple | 预设 purple 在浅色主题下的背景色;深色主题有自己的取值。--ads-tooltip-preset-purple-text 是它的文字颜色。 | #722ed1 |
| --ads-tooltip-preset-geekblue | 预设 geekblue 在浅色主题下的背景色;深色主题有自己的取值。--ads-tooltip-preset-geekblue-text 是它的文字颜色。 | #2f54eb |
| --ads-tooltip-preset-magenta | 预设 magenta 在浅色主题下的背景色;深色主题有自己的取值。--ads-tooltip-preset-magenta-text 是它的文字颜色。 | #eb2f96 |
| --ads-tooltip-preset-volcano | 预设 volcano 在浅色主题下的背景色;深色主题有自己的取值。--ads-tooltip-preset-volcano-text 是它的文字颜色。 | #fa541c |
| --ads-tooltip-preset-gold | 预设 gold 在浅色主题下的背景色;深色主题有自己的取值。--ads-tooltip-preset-gold-text 是它的文字颜色。 | #faad14 |
| --ads-tooltip-preset-lime | 预设 lime 在浅色主题下的背景色;深色主题有自己的取值。--ads-tooltip-preset-lime-text 是它的文字颜色。 | #a0d911 |
无障碍
- 提示带有
role="tooltip"和id。显示期间,触发元素带有指向它的aria-describedby(若触发元素本身不可聚焦,如包裹复选框的 label,则加在其内第一个可聚焦元素上;会与你自己设置的值合并);提示关闭时该属性被移除,因此不会指向页面上不存在的 id。 - 默认情况下,键盘聚焦和悬停都会打开提示,
Escape可在焦点停留在触发元素时关闭它。提示从不获得焦点,也不在 Tab 顺序中,指针可以移入提示并停留。 - 触发元素必须可聚焦,键盘才能到达提示:
Button、链接和输入框可以,而普通的<span>需要tabindex="0"。 - 提示起描述作用,不提供名称。仅含图标的按钮仍需要
aria-label。 - 对比度:默认提示框为
#262626底白字,对比度 15.1:1;深色主题下为#424242底白字,10.0:1。13 个预设与任意自定义color的文字取黑或白中对比度更高者,因此在浅色主题、深色主题以及使用tokens-accessible.css时都不低于 4.5:1。Ant Design 在所有预设上都使用白字,其中多数低于 4.5:1。 - 在强制颜色模式(如 Windows 高对比度)下,提示框和箭头带有系统颜色的边框,不会与页面融为一体。
- 已用真实读屏软件(Orca 搭配 Firefox)验证:在读出触发元素的名称和角色之后,它会把提示文字读作该元素的描述,先读元素原有的描述,长提示完整读出,未显示的
trigger="click"提示不会多读任何内容。未验证:NVDA、JAWS 和 VoiceOver,在读屏软件读完焦点之后才打开的提示是否会被播报(这取决于 Orca 自身的时序),以及真实的触屏设备(轻触显示提示,轻触别处关闭;仅用模拟触摸测试过)。