isElementInContainer【元素是否整体在容器内】
描述
判断是否元素 el 整体都包含在 container 容器里,返回值 Boolean
# 1.示例
容器
盒子1:【盒子1】是否存在【容器】中:否
盒子2:【盒子2】是否存在【容器】中:否
复制代码
# 2.入参说明
| 参数 | 说明 | 类型 | 是否必填 | 默认值 |
|---|---|---|---|---|
| el | 目标元素 | HTMLElement | 是 | - |
| container | 某个 dom 容器 | HTMLElement | 是 | - |
# 3.源码
源码,点开查看 👈
/**
* 判断是否元素el位置在 container容器里
* @param el
* @param container
* @returns {boolean}
*/
function isElementInContainer(el, container) {
if (!el || !container) return false
const elRect = el.getBoundingClientRect()
let containerRect
if ([window, document, document?.documentElement, null, undefined].includes(container)) {
containerRect = {
top: 0,
right: window?.innerWidth,
bottom: window?.innerHeight,
left: 0
}
} else {
containerRect = container.getBoundingClientRect()
}
return (
elRect.top < containerRect.bottom &&
elRect.bottom > containerRect.top &&
elRect.right > containerRect.left &&
elRect.left < containerRect.right
)
}
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
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
上次更新: 2025/07/01, 14:52:29