getRelativePosition
计算元素相对于指定父元素的位置坐标,用于实现相对定位功能。
函数签名
typescript
function getRelativePosition(
rect: Rect,
offsetParent?: HTMLElement
): Coords
interface Rect {
x: number
y: number
width: number
height: number
top: number
left: number
right: number
bottom: number
}
interface Coords {
x: number
y: number
}参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
rect | Rect | 是 | 元素的矩形信息,通常通过 getElementRect 获取 |
offsetParent | HTMLElement | 否 | 相对的父元素,不提供时返回相对于视口的坐标 |
返回值
| 类型 | 说明 |
|---|---|
Coords | 坐标对象,包含 x 和 y 属性 |
工作原理
有 offsetParent 参数时:
- 调用父元素的
getBoundingClientRect()获取父元素矩形 - 计算相对坐标:
x = rect.left - offsetRect.left,y = rect.top - offsetRect.top - 返回相对于父元素的坐标
- 调用父元素的
无 offsetParent 参数时:
- 直接返回
rect.left和rect.top - 即相对于视口的坐标
- 直接返回
结果可能为负值(元素在父元素左上方时)。此方法比 CSS 的 offsetLeft/offsetTop 更灵活,可以指定任意父元素。