PB04▸🪟 Overlay · 覆蓋層▸提示
Tooltip
提示氣泡
難度 ★★★★★標籤 tooltip · hover · 焦點3 min read
模式簡述
Tooltip:純資訊提示,不可互動。只在 hover/focus 顯示,移開即消失。文字應該短到一行內。
滑鼠懸停觸發
Claude Code Prompt
參考:PB04 tooltip 組件:Tooltip.tsx Tooltip:純資訊提示,不可互動。只在 hover/focus 顯示,移開即消失。文字應該短到一行內。 限制: - 延遲 0ms - 只綁 hover 不綁 focus - 手機端嘗試顯示 tooltip
完整程式碼
"use client";
import { useState } from "react";
import { Info } from "lucide-react";
type State = "hover" | "focus" | "visible";
export function Tooltip({ state = "visible" }: { state?: State }) {
const [show, setShow] = useState(false);
const visible = state === "visible" || show;
return (
<div className="grid h-[200px] w-full max-w-md place-items-center">
<div className="relative">
<button
onMouseEnter={() => setShow(true)}
onMouseLeave={() => setShow(false)}
onFocus={() => setShow(true)}
onBlur={() => setShow(false)}
className="inline-flex items-center gap-1.5 rounded-md border border-border bg-background/50 px-3 py-1.5 text-xs hover:border-lab-accent"
>
<Info className="h-3.5 w-3.5" />
說明
</button>
{visible && (
<div className="pointer-events-none absolute left-1/2 top-full z-10 mt-2 -translate-x-1/2 whitespace-nowrap rounded-md border border-border bg-background px-2.5 py-1.5 font-mono text-[11px] text-foreground shadow-lg animate-in fade-in duration-100">
<div className="absolute -top-1 left-1/2 h-2 w-2 -translate-x-1/2 rotate-45 border-l border-t border-border bg-background" />
這是 tooltip 內容
</div>
)}
<p className="mt-3 font-mono text-[10px] text-muted-foreground/60">
{state === "focus" ? "Tab 聚焦此按鈕觸發" : state === "hover" ? "滑鼠懸停觸發" : "demo: 恆顯"}
</p>
</div>
</div>
);
}何時用
- ✅ icon-only 按鈕補充文字標籤
- ✅ 縮寫或專有名詞的釋義
- ✅ 顯示快捷鍵提示
何時別用
- ❌ 承載操作按鈕(hover 出現後鼠標移過去就消失)
- ❌ 資訊重要到使用者必須讀(直接寫在介面上)
- ❌ 資訊長到要捲動
我踩過的坑
-
延遲 0ms:滑鼠經過就跳出來,亂閃。設 300-500ms delay。
-
只綁 hover 不綁 focus:鍵盤使用者完全用不到。記得 aria-describedby + focus 觸發。
-
手機端嘗試顯示 tooltip:手機沒有 hover,要嘛改成 long press,要嘛換 popover。
相關模式
- PB03
- PB09