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, чтобы подсказка была доступна с клавиатуры; в Ant Design для React по умолчанию 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: триггер по умолчанию hover и focus (в React только hover); у 13 пресетов текст чёрный или белый по контрасту, а Ant Design рисует белый; нет
defaultOpen (используйте bind:open), fresh, forceAlign и align; classNames и styles — объекты, а не функции; настройки ConfigProvider и tooltip.unique появятся вместе с компонентом ConfigProvider; потомок оборачивается элементом без собственного бокса, а anchor заменяет nzTooltipOrigin из Angular.Дизайн-токены
| Токен | Описание | По умолчанию |
|---|---|---|
| --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, ссылающийся на неё (у первого фокусируемого элемента внутри, если сам триггер не получает фокус, как метка вокруг флажка; объединяется со значением, заданным вами); при закрытии атрибут убирается, поэтому он никогда не указывает на отсутствующий на странице id. - По умолчанию подсказка открывается и при фокусе с клавиатуры, и при наведении, а
Escapeзакрывает её, пока фокус остаётся на триггере. Подсказка никогда не получает фокус и не входит в порядок Tab, а курсор может зайти в неё и оставаться там. - Чтобы подсказка была доступна с клавиатуры, триггер должен получать фокус:
Button, ссылка и поле получают, а обычному<span>нуженtabindex="0". - Подсказка описывает, но не даёт имя. Кнопке только с иконкой по-прежнему нужен
aria-label. - Контраст: стандартный блок — белый на
#262626, 15,1:1, и белый на#424242в тёмной теме, 10,0:1. Текст 13 пресетов и любого своегоcolorчёрный или белый, в зависимости от контраста, поэтому он не ниже 4,5:1 в светлой теме, в тёмной и сtokens-accessible.css. Ant Design рисует белый на каждом пресете, и на большинстве из них контраст ниже 4,5:1. - В режимах принудительных цветов, например в высокой контрастности Windows, блок и стрелка рисуются с рамкой системного цвета и не сливаются со страницей.
- Проверено настоящим скринридером (Orca с Firefox): после имени и роли элемента он читает текст подсказки как его описание, сначала прежнее описание элемента, длинную подсказку целиком и ничего лишнего для подсказки
trigger="click", которая не показана. Не проверено: NVDA, JAWS и VoiceOver, объявляется ли подсказка, которая открылась после того, как скринридер уже произнёс фокус (это зависит от собственных задержек Orca), и настоящее сенсорное устройство (касание показывает подсказку, касание в другом месте закрывает её; проверено только эмуляцией касаний).