---
title: "Tooltip"
description: "Небольшое окно с подробностями, которое появляется при наведении мыши на элемент."
canonical_url: "https://b24-ui.bx-shef.by/docs/components/tooltip"
---
# Tooltip

> Небольшое окно с подробностями, которое появляется при наведении мыши на элемент.

## Использование

Поместите в слот по умолчанию Tooltip [Button](https://b24-ui.bx-shef.by/raw/docs/components/button.md) или любой другой компонент.

```vue
<template>
  <B24Tooltip text="Открыть на GitHub">
<B24Button label="Open" />
</B24Tooltip>
</template>
```

> [!WARNING]
> Оберните приложение в компонент [`App`](https://b24-ui.bx-shef.by/raw/docs/components/app.md): он использует компонент [`TooltipProvider`](https://reka-ui.com/docs/components/tooltip#provider) из Reka UI.

> [!TIP]
> See: /docs/components/app/#props
> Пропс `tooltip` компонента `App` показывает, как настроить Tooltip глобально.

### Текст

Пропс `text` задаёт содержимое Tooltip.

```vue
<template>
  <B24Tooltip text="Открыть на GitHub">
<B24Button label="Open" />
</B24Tooltip>
</template>
```

### Клавиши

Пропс `kbds` отрисовывает в Tooltip компоненты [Kbd](https://b24-ui.bx-shef.by/raw/docs/components/kbd.md).

```vue
<template>
  <B24Tooltip text="Открыть на GitHub" :kbds="{'0':'meta','1':'G'}">
<B24Button label="Open" />
</B24Tooltip>
</template>
```

> [!TIP]
> Можно использовать специальные клавиши, например `meta`: на macOS она отображается как `⌘`, на остальных платформах как `Ctrl`.

### Задержка

Пропс `delay-duration` меняет задержку перед появлением Tooltip. Например, значение `0` показывает его сразу.

```vue
<template>
  <B24Tooltip :delay-duration="0" text="Открыть на GitHub">
<B24Button label="Open" />
</B24Tooltip>
</template>
```

> [!TIP]
> Глобально это настраивается опцией `tooltip.delayDuration` в компоненте [`App`](https://b24-ui.bx-shef.by/raw/docs/components/app.md).

### Содержимое

Пропс `content` управляет отрисовкой содержимого Tooltip, например его `align` или `side`.

> [!TIP]
> Глобально это настраивается опцией `tooltip.content` в компоненте [`App`](https://b24-ui.bx-shef.by/raw/docs/components/app.md).

```vue
<template>
  <B24Tooltip :content="{align:'center',side:'bottom',sideOffset:8}" text="Открыть на GitHub">
<B24Button label="Open" />
</B24Tooltip>
</template>
```

### Стрелка

Пропс `arrow` показывает стрелку у Tooltip.

```vue
<template>
  <B24Tooltip text="Открыть на GitHub">
<B24Button label="Open" />
</B24Tooltip>
</template>
```

### Отключение

Пропс `disabled` отключает Tooltip.

```vue
<template>
  <B24Tooltip disabled text="Открыть на GitHub">
<B24Button label="Open" />
</B24Tooltip>
</template>
```

## Примеры

### Управление открытием

Состоянием открытия управляют пропс `default-open` или директива `v-model:open`.

```vue [TooltipOpenExample.vue]
<script setup lang="ts">
const open = ref(false)

defineShortcuts({
  o: () => open.value = !open.value
})
</script>

<template>
  <B24Tooltip v-model:open="open" text="Открыть на GitHub">
    <B24Button label="Открыть" />
  </B24Tooltip>
</template>
```

> [!NOTE]
> В этом примере с помощью [`defineShortcuts`](https://b24-ui.bx-shef.by/raw/docs/composables/define-shortcuts.md) Tooltip переключается по нажатию <kbd value="O">
> </kbd>
> .

### С привязкой к курсору

Чтобы Tooltip следовал за курсором при наведении на элемент, используйте пропс [`reference`](https://reka-ui.com/docs/components/tooltip#trigger):

```vue [TooltipCursorExample.vue]
<script setup lang="ts">
const open = ref(false)
const anchor = ref({ x: 0, y: 0 })

const reference = computed(() => ({
  getBoundingClientRect: () =>
    ({
      width: 0,
      height: 0,
      left: anchor.value.x,
      right: anchor.value.x,
      top: anchor.value.y,
      bottom: anchor.value.y,
      ...anchor.value
    } as DOMRect)
}))
</script>

<template>
  <B24Tooltip
    :open="open"
    :reference="reference"
    :content="{ side: 'top', sideOffset: 16, updatePositionStrategy: 'always' }"
  >
    <div
      class="flex items-center justify-center rounded-md border border-dashed border-(--ui-color-accent-main-primary-alt) text-sm aspect-video w-72"
      @pointerenter="open = true"
      @pointerleave="open = false"
      @pointermove="(ev: PointerEvent) => {
        anchor.x = ev.clientX
        anchor.y = ev.clientY
      }"
    >
      Наведите на меня
    </div>

    <template #content>
      {{ anchor.x.toFixed(0) }} - {{ anchor.y.toFixed(0) }}
    </template>
  </B24Tooltip>
</template>
```

### Иконка справки

Tooltip можно сочетать с [иконкой](https://bitrix24.github.io/b24icons/icons/).

```vue [TooltipHelpIconExample.vue]
<script setup lang="ts">
import HelpIcon from '@bitrix24/b24icons-vue/main/HelpIcon'
</script>

<template>
  <B24Tooltip
    :delay-duration="100"
    :content="{ side: 'right' }"
    text="Когда исполнитель завершит задачу, она придёт к вам на проверку. Вы можете принять работу (и задача будет закрыта) или вернуть задачу на доработку."
  >
    <HelpIcon class="size-5 cursor-help" />
  </B24Tooltip>
</template>
```

## API

### Пропсы

```ts
/**
 * Props for the Tooltip component
 */
interface TooltipProps {
  /**
   * The text content of the tooltip.
   */
  text?: string | undefined;
  /**
   * The keyboard keys to display in the tooltip.
   */
  kbds?: (string | undefined)[] | KbdProps[] | undefined;
  /**
   * The content of the tooltip.
   * 
   * Inherits from the `tooltip.content` of the {@link AppProps } component when not provided.
   * @default { side: 'bottom', sideOffset: 8, collisionPadding: 8 }
   */
  content?: Omit<TooltipContentProps, "as" | "asChild"> & Partial<EmitsToProps<TooltipContentImplEmits>> | undefined;
  /**
   * Display an arrow alongside the tooltip.
   * `{ rounded: true }`
   * @default true
   */
  arrow?: boolean | Omit<TooltipArrowProps, "as" | "asChild"> | undefined;
  /**
   * Render the tooltip in a portal.
   * @default true
   */
  portal?: string | false | true | HTMLElement | undefined;
  /**
   * The reference (or anchor) element that is being referred to for positioning.
   * 
   * If not provided will use the current component as anchor.
   */
  reference?: Element | VirtualElement | undefined;
  b24ui?: { content?: SlotClass; arrow?: SlotClass; text?: SlotClass; kbds?: SlotClass; kbdsSize?: SlotClass; kbdsAccent?: SlotClass; } | undefined;
  /**
   * The open state of the tooltip when it is initially rendered.
   * Use when you do not need to control its open state.
   */
  defaultOpen?: boolean | undefined;
  /**
   * The controlled open state of the tooltip.
   */
  open?: boolean | undefined;
  /**
   * Override the duration given to the `Provider` to customise
   * the open delay for a specific tooltip.
   * @default 700
   */
  delayDuration?: number | undefined;
  /**
   * Prevents Tooltip.Content from remaining open when hovering.
   * Disabling this has accessibility consequences. Inherits
   * from Tooltip.Provider.
   */
  disableHoverableContent?: boolean | undefined;
  /**
   * When `true`, clicking on trigger will not close the content.
   * @default false
   */
  disableClosingTrigger?: boolean | undefined;
  /**
   * When `true`, disable tooltip
   * @default false
   */
  disabled?: boolean | undefined;
  /**
   * Prevent the tooltip from opening if the focus did not come from
   * the keyboard by matching against the `:focus-visible` selector.
   * This is useful if you want to avoid opening it when switching
   * browser tabs or closing a dialog.
   * @default false
   */
  ignoreNonKeyboardFocus?: boolean | undefined;
}
```

### Слоты

```ts
/**
 * Slots for the Tooltip component
 */
interface TooltipSlots {
  default(): any;
  content(): any;
}
```

### События

```ts
/**
 * Emitted events for the Tooltip component
 */
interface TooltipEmits {
  update:open: (payload: [value: boolean]) => void;
}
```

## Тема

```ts [app.config.ts]
export default defineAppConfig({
  b24ui: {
    tooltip: {
      slots: {
        content: 'light flex flex-row items-center justify-between gap-[5px] will-change-[opacity] min-h-[37px] shadow-xl/20 select-none motion-safe:data-[state=delayed-open]:animate-[scale-in_100ms_var(--ease-out)] motion-safe:data-[state=closed]:animate-[scale-out_100ms_var(--ease-out)] p-[13px] text-(length:--ui-font-size-lg)/[normal] font-[family-name:var(--ui-font-family-system)] bg-(--ui-color-bg-content-inapp) text-(--ui-color-base-8) rounded-[calc(var(--ui-border-radius-3xl)-2px)] ring ring-(--ui-color-bg-content-inapp) origin-(--reka-tooltip-content-transform-origin) pointer-events-auto',
        arrow: 'fill-(--ui-color-bg-content-inapp) stroke-(--ui-color-bg-content-inapp)',
        text: 'text-pretty max-w-[344px] min-w-[100px]',
        kbds: "hidden lg:inline-flex items-center shrink-0 gap-0.5 not-first-of-type:before:content-[''] not-first-of-type:before:me-0.5",
        kbdsSize: 'sm',
        kbdsAccent: 'default'
      }
    }
  }
})
```

## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
