业务说明
有很多时候,进行图片懒加载
或长列表元素滚动优化
时,就要判断当前元素是否在视窗内可见
原理
计算出当前元素相对目标元素的位置,比如上下左右分别是多少,就可以知道是不是在某一个视窗内;
具体可以用到Element.getBoundingClientRect()
这个方法,MDN查看详情

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

代码部分:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
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地址