下拉气泡定位
灵感:能力工具箱 floating-ui(Floating UI 计算下拉/气泡定位)。
> 小四原创:锚点 + 浮层 → computePosition → 写 top/left。
> 配合 flip/shift 防出屏。
何时使用
- 自定义下拉菜单贴按钮
- 自研气泡/ Popover 定位
- Demo 字段旁浮层
硬约束
- 依赖:
@floating-ui/dom。 - 打开浮层后调用定位;滚动/resize 可节流重算。
- 实现要点注释标 小四原创。
- 不做完整 Headless UI 套件。
推荐实现
import { computePosition, flip, shift, offset } from '@floating-ui/dom'
// 小四原创:锚点 → 浮层定位
export async function placeFloating(
reference: HTMLElement,
floating: HTMLElement,
opts?: { placement?: 'bottom-start' | 'top-start' | 'right' | 'left' },
): Promise<void> {
const { x, y } = await computePosition(reference, floating, {
placement: opts?.placement ?? 'bottom-start',
middleware: [offset(6), flip(), shift({ padding: 8 })],
})
Object.assign(floating.style, {
position: 'absolute',
left: `${x}px`,
top: `${y}px`,
})
}
Agent 步骤
npm i @floating-ui/dom。- 下拉打开时
placeFloating(btn, menu)。 - 自测:贴底时自动 flip;靠边 shift 不裁切。
不要做
- 写死
top:100%却声称已用 Floating UI。 - 与 tippy 同场景重复造两套气泡。
附加
- README.md · reference.md · templates/usage.md