computePosition
计算弹出层位置,根据参考元素的位置和尺寸计算弹出层应该显示的绝对位置。
函数签名
typescript
function computePosition(
placement: Placement,
reference: Rect,
floating: { width: number; height: number },
scrollOffset: Coords
): Coords
type Placement =
| 'top' | 'top-start' | 'top-end'
| 'bottom' | 'bottom-start' | 'bottom-end'
| 'left' | 'left-start' | 'left-end'
| 'right' | 'right-start' | 'right-end'
interface Rect {
x: number
y: number
width: number
height: number
}
interface Coords {
x: number
y: number
}参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
placement | Placement | 是 | 定位方式(如 'top', 'bottom-start' 等) |
reference | Rect | 是 | 参考元素的位置和尺寸信息 |
floating | { width: number; height: number } | 是 | 弹出层的尺寸信息 |
scrollOffset | Coords | 是 | 页面滚动偏移量,用于转换为绝对坐标 |
返回值
| 类型 | 说明 |
|---|---|
Coords | 弹出层的绝对位置坐标(相对于页面,包含滚动偏移) |
工作原理
- 解析placement:提取基础方向(top/bottom/left/right)和对齐方式(start/end)
- 计算基础位置:根据基础方向计算弹出层的初始位置
top: 弹出层在参考元素上方,水平居中bottom: 弹出层在参考元素下方,水平居中left: 弹出层在参考元素左侧,垂直居中right: 弹出层在参考元素右侧,垂直居中
- 应用对齐方式:根据对齐方式调整位置
start: 与参考元素的起始边对齐end: 与参考元素的结束边对齐
- 添加滚动偏移:将视口坐标转换为页面绝对坐标
- 返回最终坐标:返回包含滚动偏移的绝对位置
支持12种定位方式(4个基础方向 + 8个带对齐的方向),返回的坐标是相对于页面的绝对位置(包含滚动偏移)。