isElementVisibleInViewport【是否可见在某个股东元素上】 🔥
描述
判断是否元素 el 当前是否 可见在某个滚动元素上。
有个原生方法,IntersectionObserver (opens new window) 兼容性不是太好。,不过这个是相对于整个屏幕可视区域,不能定制划到某个特定滚动元素
# 1.示例
第8个box 部分可见:
否
第8个box 全部可见: 否
第20个box 部分可见: 否
第20个box 全部可见: 否
复制代码
# 2.入参说明
| 参数 | 说明 | 类型 | 是否必填 | 默认值 |
|---|---|---|---|---|
| el | 目标元素 | HTMLElement | 是 | - |
| elScrollView | 滚动区域元素,不传默认是 body 滚动元素 | HTMLElement | - | - |
| partiallyVisible | 是否部分显示 | Boolean | - | true |
| direction | 方向 可选值 horizontal(水平) vertical(垂直), 默认值 vertical | String | - | - |
| offsetTop | 顶部偏移量 | Number | - | vertical |
| offsetBottom | 底部偏移量 | Number | - | 0 |
| offsetLeft | 左部偏移量 | Number | - | 0 |
| offsetRight | 右部偏移量 | Number | - | 0 |
# 3.源码
源码,点开查看 👈
/**
* 检查指定的元素是否在视口中可见。
* @param el 目标元素
* @param elScrollView 滚动区域元素
* @param partiallyVisible 是否部分显示
* @param direction 方向 可选值 horizontal(水平) vertical(垂直), 默认值 vertical
* @param offsetTop 顶部偏移量
* @param offsetBottom 底部偏移量
* @param offsetLeft 左部偏移量
* @param offsetRight 右部偏移量
* @returns {boolean}
*/
function isElementVisibleInViewport({
el,
elScrollView,
partiallyVisible = true,
direction = 'vertical', // horizontal vertical
offsetTop = 0,
offsetBottom = 0,
offsetLeft = 0,
offsetRight = 0
}) {
if (!elScrollView) {
elScrollView = document.documentElement || document.body
}
const elRect = el.getBoundingClientRect()
const elScrollViewRect = elScrollView.getBoundingClientRect()
if (direction === 'vertical') {
return partiallyVisible
? elRect.bottom > elScrollViewRect.top + offsetTop && elRect.top < elScrollViewRect.bottom + offsetBottom
: elRect.top > elScrollViewRect.top + offsetTop && elRect.bottom < elScrollViewRect.bottom + offsetBottom
} else if (direction === 'horizontal') {
return partiallyVisible
? elRect.right > elScrollViewRect.left + offsetLeft && elRect.left < elScrollViewRect.right + offsetRight
: elRect.left > elScrollViewRect.left + offsetLeft && elRect.right < elScrollViewRect.right + offsetRight
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
上次更新: 2025/07/01, 14:52:29