getAbsOffsetTop【距离父滚动区域顶部绝对距离】 🔥
描述
获取目标 dom 在父滚动区域内 距离父滚动区域顶部绝对距离。
# 1.示例
.ex-scroll-view__wrap 容器
box-1
box-2
box-3
box-4
复制代码
# 说明:
# 2.入参说明
| 参数 | 说明 | 类型 | 是否必填 | 默认值 |
|---|---|---|---|---|
| el | 目标 dom 元素 | HTMLElement String | - | - |
| elWrap | 目标 dom 元素最近的父滚动容器 | DomElement String | - | - |
| offsetTop | 自定义的偏移量 | Number | - | - |
# 3.源码
源码,点开查看 👈
/**
* 获取dom在滚动区域绝对位置top
* @param el dom节点属性(id、class)或 目标dom元素
* @param elWrap 滚动dom节点
* @param offsetTop 偏移量
* */
function getAbsOffsetTop(el, elWrap, offsetTop = 0) {
if (!el || !elWrap) return 0
if (typeof el == 'string') {
el = document?.querySelector(el)
}
if (typeof elWrap == 'string') {
elWrap = document?.querySelector(elWrap)
}
if (!el || !elWrap) return 0
const elRect = el.getBoundingClientRect()
const elWrapRect = elWrap.getBoundingClientRect()
return ~~elRect.top - ~~elWrapRect.top + ~~elWrap.scrollTop - ~~offsetTop
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
上次更新: 2025/07/01, 14:52:29