Skip to content

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
}

参数

参数名类型必填说明
placementPlacement定位方式(如 'top', 'bottom-start' 等)
referenceRect参考元素的位置和尺寸信息
floating{ width: number; height: number }弹出层的尺寸信息
scrollOffsetCoords页面滚动偏移量,用于转换为绝对坐标

返回值

类型说明
Coords弹出层的绝对位置坐标(相对于页面,包含滚动偏移)

工作原理

  1. 解析placement:提取基础方向(top/bottom/left/right)和对齐方式(start/end)
  2. 计算基础位置:根据基础方向计算弹出层的初始位置
    • top: 弹出层在参考元素上方,水平居中
    • bottom: 弹出层在参考元素下方,水平居中
    • left: 弹出层在参考元素左侧,垂直居中
    • right: 弹出层在参考元素右侧,垂直居中
  3. 应用对齐方式:根据对齐方式调整位置
    • start: 与参考元素的起始边对齐
    • end: 与参考元素的结束边对齐
  4. 添加滚动偏移:将视口坐标转换为页面绝对坐标
  5. 返回最终坐标:返回包含滚动偏移的绝对位置

支持12种定位方式(4个基础方向 + 8个带对齐的方向),返回的坐标是相对于页面的绝对位置(包含滚动偏移)。