判断元素是否在视窗内

业务说明

有很多时候,进行图片懒加载长列表元素滚动优化时,就要判断当前元素是否在视窗内可见

原理

计算出当前元素相对目标元素的位置,比如上下左右分别是多少,就可以知道是不是在某一个视窗内;

具体可以用到Element.getBoundingClientRect()这个方法,MDN查看详情

示例

具体实现

自己写了一个简单的DEMO,判断小的元素,是否在大元素盒子之内,两者的比较,都是top、bottom、left、right的值进行比较;
DEMO示例

代码部分:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @description: 判断是否在目标视窗内
* @param {String} curEle: 当前元素
* @param {String} targetEle: 目标元素
* @return {Boolean} true or false
*/
const calc = (curEle = null, targetEle = null) => {
const _curEle = document.querySelector(curEle)
if(!curEle || !_curEle)return
const {top: curTop,bottom:curBottom,left:curLeft,right:curRight} = _curEle.getBoundingClientRect()
let _targetEle = targetEle || document.documentElement
_targetEle = document.querySelector(_targetEle)
const {top: targetTop,bottom:targetBottom,left:targetLeft,right:targetRight} = _targetEle.getBoundingClientRect()

let res = false
if (curTop >= targetTop && curBottom <= targetBottom && curLeft >= targetLeft && curRight <= targetRight) {
res = true
}
return res
}

具体DEMO

github地址


判断元素是否在视窗内
https://liujiaweb.cn/posts/1692.html
作者
Liu Jia
发布于
2020年8月12日
许可协议