@data-slot/tooltip

中文文档
1.1.3发布于 2026/11/05MITTypeScriptESM + CJS构建来源已验证近 30 天下载 5592

Headless tooltip component for vanilla JavaScript. Accessible, unstyled, tiny.

原始使用文档
文档目录14 节
  1. Installation
  2. Quick Start
  3. API
  4. Initialization
  5. Slots
  6. Data Attributes
  7. Options
  8. Controller
  9. Content mounting and server rendering
  10. Events
  11. Styling
  12. Accessibility
  13. Behavior
  14. License

@data-slot/tooltip

Headless tooltip component for vanilla JavaScript. Accessible, unstyled, tiny.

Installation

npm install @data-slot/tooltip

Quick Start

<div data-slot="tooltip">
  <button data-slot="tooltip-trigger">Hover me</button>
  <div data-slot="tooltip-content" hidden>
    Helpful tooltip text
  </div>
</div>

<script type="module">
  import { create } from "@data-slot/tooltip";
  
  const controllers = create();
</script>

API

Initialization

create(scope?)

Auto-discover and bind all tooltip instances in a scope (defaults to document).

import { create } from "@data-slot/tooltip";

const controllers = create(); // Returns TooltipController[]

createTooltip(root, options?)

Create a controller for a specific element.

import { createTooltip } from "@data-slot/tooltip";

const tooltip = createTooltip(element, {
  delay: 300,
  skipDelayDuration: 300,
  side: "top",
  align: "center",
  onOpenChange: (open) => console.log(open),
});

Slots

Runtime Slots

  • tooltip - Root element that manages the open state and hover delays.
  • tooltip-trigger - Required element that opens the tooltip on hover or focus and is linked to its description.
  • tooltip-content - Required floating panel with tooltip semantics.
  • tooltip-arrow - Optional arrow inside the content, positioned against the trigger by the runtime.
  • tooltip-positioner - Optional authored positioning wrapper around the content, reused instead of a generated wrapper.
  • tooltip-portal - Optional authored portal wrapper that can contain the positioner and content.

Markup

<div data-slot="tooltip">
  <button data-slot="tooltip-trigger">Trigger</button>
  <div data-slot="tooltip-content">
    Content
    <div data-slot="tooltip-arrow"></div>
  </div>
</div>

Composed Portal Markup (Optional)

<div data-slot="tooltip">
  <button data-slot="tooltip-trigger">Trigger</button>
  <div data-slot="tooltip-portal">
    <div data-slot="tooltip-positioner">
      <div data-slot="tooltip-content">
        Content
        <div data-slot="tooltip-arrow"></div>
      </div>
    </div>
  </div>
</div>

Data Attributes

Options can also be set via data attributes. JS options take precedence.

Placement attributes (data-side, data-align, data-side-offset, data-align-offset, data-avoid-collisions, data-collision-padding) resolve in this order:

  1. JavaScript option
  2. tooltip-content
  3. tooltip-positioner
  4. tooltip root (fallback)
AttributeTypeDefaultDescription
data-delaynumber300Delay before showing tooltip (ms)
data-skip-delay-durationnumber300Duration to skip delay after closing (ms)
data-sidestring"top"Side relative to trigger (top, right, bottom, left, inline-start, inline-end)
data-alignstring"center"Alignment along the side
data-side-offsetnumber4Distance from trigger (px)
data-align-offsetnumber0Alignment edge offset (px)
data-avoid-collisionsbooleantrueCollision handling
data-collision-paddingnumber8Viewport edge padding (px)
data-portalbooleantruePortal while open
data-mount-strategy (root)"lazy" | "eager""lazy"Detach closed content, or retain it in the document
<!-- Tooltip with faster response -->
<div data-slot="tooltip" data-delay="100">
  ...
</div>

<!-- Disable warm-up behavior -->
<div data-slot="tooltip" data-skip-delay-duration="0">
  ...
</div>

<!-- Side/align and offsets on content element -->
<div
  data-slot="tooltip-content"
  data-side="bottom"
  data-align="start"
  data-side-offset="8"
  data-align-offset="4"
>
  ...
</div>

Output Attributes

The component sets these attributes automatically:

ElementAttributeValues
Rootdata-state"open" | "closed" (legacy compatibility)
Rootdata-open / data-closedPresent when matching state
Rootdata-instant"delay" | "focus" | "dismiss"
Contentdata-state"open" | "closed" (legacy compatibility)
Contentdata-open / data-closedPresent when matching state
Contentdata-starting-stylePresent while opening
Contentdata-ending-stylePresent while closing
Contentdata-instant"delay" | "focus" | "dismiss"
Contentdata-side"top" | "right" | "bottom" | "left" | "inline-start" | "inline-end"
Contentdata-align"start" | "center" | "end"
Contentrole"tooltip"
Contentaria-hidden"true" when closed, "false" when open
Positionerdata-open / data-closedPresent when matching state
Positionerdata-instant"delay" | "focus" | "dismiss"
Positionerdata-side"top" | "right" | "bottom" | "left" | "inline-start" | "inline-end"
Positionerdata-align"start" | "center" | "end"
Arrowdata-open / data-closedPresent when matching state
Arrowdata-instant"delay" | "focus" | "dismiss"
Arrowdata-side"top" | "right" | "bottom" | "left" | "inline-start" | "inline-end"
Arrowdata-align"start" | "center" | "end"
Arrowdata-uncenteredPresent when the arrow cannot stay perfectly centered
Arrowaria-hidden"true"
Triggeraria-describedbyContent ID when open, removed when closed

Options

OptionTypeDefaultDescription
delaynumber300Delay before showing tooltip (ms)
skipDelayDurationnumber300Duration to skip delay after closing (ms). Set to 0 to disable warm-up.
side"top" | "right" | "bottom" | "left" | "inline-start" | "inline-end""top"Preferred side relative to trigger
align"start" | "center" | "end""center"Preferred alignment
sideOffsetnumber4Distance from trigger in pixels
alignOffsetnumber0Offset from alignment edge in pixels
avoidCollisionsbooleantrueFlip/shift to stay in viewport
collisionPaddingnumber8Viewport edge padding in pixels
portalbooleantruePortal content to document.body while open
mountStrategy"lazy" | "eager""lazy"Detach closed content; JS overrides root data-mount-strategy
onOpenChange(open: boolean) => voidundefinedCallback when visibility changes

Note: side and align are preferred placement inputs resolved at bind time. With collision handling enabled, computed data-side can differ at runtime.

Controller

Method/PropertyDescription
show()Show the tooltip immediately. Respects disabled state.
hide()Hide the tooltip
isOpenCurrent visibility state (readonly boolean)
destroy()Cleanup all event listeners and timers

Controller Destruction

destroy() permanently disposes the controller and hides any open surface without emitting an additional change event. Repeated destruction is safe; methods on the old controller become no-ops. Create a new controller on the same root to rebind it.

Cleanup removes the description reference added by this tooltip and preserves other authored aria-describedby references. An authored reference to the tooltip itself is suspended while its content is detached and restored on destruction.

Content mounting and server rendering

By default, Tooltip removes its hidden message from the page’s DOM. This keeps pages with many tooltips smaller after initialization. The button or other element that opens the tooltip stays in the page.

Showing the tooltip puts the same message back into the page. Its state and event listeners are preserved. Hiding it waits for any exit animation to finish before removing it. If the tooltip opens again during that animation, it stays in the page.

Most applications can use this default without any changes.

If your code needs to find or update the message while the tooltip is hidden—for example, using querySelector—use eager mode to keep it in the DOM:

createTooltip(root, { mountStrategy: "eager" });

You can also add data-mount-strategy="eager" to the Tooltip root. A JavaScript option takes precedence over the HTML attribute.

With the default lazy mode, DOM queries won’t find the hidden message. If you only need to change its text, you can also keep a reference to the message element before initializing Tooltip and use that reference later.

Server rendering and pages without JavaScript

Lazy mounting does not reduce the HTML sent to the browser. The message is still included in your HTML; Tooltip removes it from the DOM after JavaScript initializes.

Keep the tooltip’s initial markup hidden to prevent it briefly appearing before initialization. The button or element that opens it must have a clear accessible name of its own. Use the tooltip for extra information, and keep anything essential available without opening it. Neither lazy nor eager mode makes a tooltip work without JavaScript.

Events

Outbound Events

Listen for changes via custom events:

element.addEventListener("tooltip:change", (e) => {
  const { open, trigger, content, reason } = e.detail;
  console.log(`Tooltip ${open ? 'opened' : 'closed'} via ${reason}`);
});
Event Detail
PropertyTypeDescription
openbooleanCurrent visibility state
triggerHTMLElementThe trigger element
contentHTMLElementThe content element
reasonstringWhat caused the change: "pointer", "focus", "blur", "escape", "api"

Inbound Events

Control the tooltip via events:

EventDetailDescription
tooltip:set{ open: boolean }Set visibility programmatically
// Show the tooltip
element.dispatchEvent(
  new CustomEvent("tooltip:set", { detail: { open: true } })
);

// Hide the tooltip
element.dispatchEvent(
  new CustomEvent("tooltip:set", { detail: { open: false } })
);

Note: Opening respects disabled state (trigger has disabled attribute or aria-disabled="true"). Closing is always allowed.

Deprecated Shapes

The following attributes and shapes are deprecated and will be removed in v1.0:

  • Legacy data-state="open|closed" styling on tooltip root and tooltip-content

Use data-open / data-closed, data-starting-style, data-ending-style, and data-instant instead.

// Deprecated: { value: boolean }
element.dispatchEvent(
  new CustomEvent("tooltip:set", { detail: { value: true } })
);

Use { open: boolean } instead.

Styling

Position is computed in JavaScript and applied to the positioner as position: absolute + transform: translate3d(...). By default, content is portaled to document.body while open. The positioned element (tooltip-positioner, or tooltip-content when portal is disabled) gets --transform-origin, which tooltip-content can use for transform animations via CSS inheritance. Use data-open / data-closed, data-starting-style / data-ending-style, data-side, data-align, and data-instant for styling and animations. Placement uses layout dimensions, so scale/zoom animations on tooltip-content remain stable without adding an extra wrapper. Tooltip arrow geometry is runtime-owned: the controller writes inline top / left coordinates and position: absolute on tooltip-arrow. CSS should only handle edge attachment, rotation, and optional cosmetic nudges. Avoid overriding the arrow cross-axis with helpers like top-1/2, left-1/2, or -translate-y-1/2.

The example below matches the Base/shadcn composition style: real tooltip-arrow, logical side support, and valued data-instant.

[data-slot="tooltip-content"] {
  position: absolute;
  display: inline-flex;
  align-items: center;
  gap: 0.375rem;
  padding: 0.375rem 0.75rem;
  font-size: 0.75rem;
  white-space: nowrap;
  background: #111827;
  color: white;
  opacity: 0;
  visibility: hidden;
  pointer-events: none;
  transform-origin: var(--transform-origin, center center);
  --tooltip-slide-x: 0px;
  --tooltip-slide-y: 0px;
  transition: opacity 0.15s ease, visibility 0s linear 0.15s;
}

[data-slot="tooltip-content"][data-side="top"] { --tooltip-slide-y: 8px; }
[data-slot="tooltip-content"][data-side="bottom"] { --tooltip-slide-y: -8px; }
[data-slot="tooltip-content"][data-side="left"] { --tooltip-slide-x: 8px; }
[data-slot="tooltip-content"][data-side="right"] { --tooltip-slide-x: -8px; }
[data-slot="tooltip-content"][data-side="inline-start"] { --tooltip-slide-x: 8px; }
[data-slot="tooltip-content"][data-side="inline-end"] { --tooltip-slide-x: -8px; }

[data-slot="tooltip-content"][data-open] {
  opacity: 1;
  visibility: visible;
  pointer-events: auto;
  transition-delay: 0s;
}

[data-slot="tooltip-content"][data-closed] {
  pointer-events: none;
}

[data-slot="tooltip-content"][data-instant] {
  transition: none;
  animation: none;
}

[data-slot="tooltip-arrow"] {
  width: 0.625rem;
  height: 0.625rem;
  background: inherit;
  transform: rotate(45deg);
}

[data-slot="tooltip-arrow"][data-side="top"] { bottom: -0.25rem; }
[data-slot="tooltip-arrow"][data-side="bottom"] { top: -0.25rem; }
[data-slot="tooltip-arrow"][data-side="left"] {
  right: -0.25rem;
  transform: translateX(-1.5px) rotate(45deg);
}
[data-slot="tooltip-arrow"][data-side="right"] {
  left: -0.25rem;
  transform: translateX(1.5px) rotate(45deg);
}
[data-slot="tooltip-arrow"][data-side="inline-start"] {
  right: -0.25rem;
  transform: translateX(-1.5px) rotate(45deg);
}
[data-slot="tooltip-arrow"][data-side="inline-end"] {
  left: -0.25rem;
  transform: translateX(1.5px) rotate(45deg);
}

Tailwind Example

Use content and arrow data attributes for open-state styling:

<div data-slot="tooltip">
  <button data-slot="tooltip-trigger">
    Hover me
  </button>
  <div
    data-slot="tooltip-content"
    data-side="top"
    class="px-2 py-1
           bg-gray-900 text-white text-sm
           opacity-0 pointer-events-none transition-opacity duration-150
           data-[open]:opacity-100 data-[open]:pointer-events-auto
           data-[instant]:transition-none"
  >
    Tooltip text
    <div
      data-slot="tooltip-arrow"
      class="absolute size-2.5 rotate-45 bg-gray-900
             data-[side=top]:-bottom-1
             data-[side=bottom]:-top-1
             data-[side=left]:-right-1
             data-[side=left]:-translate-x-[1.5px]
             data-[side=right]:-left-1
             data-[side=right]:translate-x-[1.5px]
             data-[side=inline-start]:-right-1
             data-[side=inline-start]:-translate-x-[1.5px]
             data-[side=inline-end]:-left-1
             data-[side=inline-end]:translate-x-[1.5px]"
    ></div>
  </div>
</div>

Accessibility

The component automatically handles:

  • role="tooltip" on content
  • aria-describedby on trigger only when open (prevents stale announcements)
  • aria-hidden on content: explicit "true"/"false" for consistent AT behavior
  • Unique ID generation for content via ensureId

Disabled Triggers

If the trigger has disabled attribute or aria-disabled="true":

  • Pointer and focus events will not open the tooltip
  • Programmatic .show() also respects the disabled state

Behavior

Warm-up Behavior

When a user closes one tooltip and quickly hovers another, the second tooltip shows instantly (no delay). This creates a fluid browsing experience similar to native OS tooltips.

  • Controlled by skipDelayDuration option
  • Set to 0 to disable this behavior
  • Warm-up opens and warm handoff closes use data-instant="delay"
  • Focus-triggered opens use data-instant="focus"
  • Dismiss-style closes (for example Escape) use data-instant="dismiss"
  • Warm window is set only when a tooltip actually closes (not when a pending open is cancelled)

Interaction Model

InputBehavior
Pointer enter trigger (mouse/pen)Show after delay
Pointer leave triggerHide immediately (unless entering content)
Pointer enter contentKeep open (hoverable content)
Pointer leave contentHide immediately (unless entering trigger)
Touch hoverIgnored (focus-only on touch devices)
Click triggerCancel a pending delayed open, or dismiss an already-open tooltip
FocusShow after delay (immediately during the warm-up window)
BlurHide immediately
EscapeHide immediately (listener only active when open)

Hoverable Content: Moving the pointer from trigger to content (or vice versa) keeps the tooltip open. This allows users to interact with links or selectable text in tooltips.

Focus Priority: While the trigger has keyboard focus, the tooltip stays open even if the pointer leaves. This prevents jarring closures during keyboard navigation.

License

MIT

版本与发布记录

@data-slot/tooltip 共发布 164 个版本,首次发布于 2026/01/09;过去 12 个月发布了 164 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.1.3latest2026/11/056 天前
1.1.22026/10/1428 天前
1.1.12026/10/051 个月前
1.1.02026/10/021 个月前
1.0.22026/09/271 个月前
1.0.12026/09/261 个月前

关于 @data-slot/tooltip 的常见问题

@data-slot/tooltip 是什么?

Headless tooltip component for vanilla JavaScript. Accessible, unstyled, tiny.

如何安装 @data-slot/tooltip?

在项目目录运行 npm install @data-slot/tooltip,或使用 pnpm add / yarn add / bun add。

@data-slot/tooltip 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@data-slot/tooltip 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@data-slot/tooltip 可以商用吗?

@data-slot/tooltip 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@data-slot/tooltip 的下载量有多少?

根据 npm 官方下载统计,@data-slot/tooltip 在 2026/10/12 – 2026/11/10 这 30 天内被下载 5,592 次,日均约 186 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@data-slot/tooltip 还在维护吗?

最新版本 1.1.3 发布于 2026/11/05(6 天前);至今共发布 164 个版本,其中过去 12 个月发布了 164 个;首次发布于 2026/01/09。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。