// dom元素是否在可视区
export const elementIsVisibleInViewport = (el, partiallyVisible = true) => {
// 第一个参数是element 第二个参数是 是否部分可见也算可见
// 设置为false 即有一部份不可见即不可见
// 设置为true 即部分可见即算是可见
const {
top,
left,
bottom,
right,
} = el.getBoundingClientRect();
const {
innerHeight,
innerWidth,
} = window;
// dom的width小于window.innerWidth及dom的高度小于window.innerHeight的情况
const case1 = ((top >= 0 && top < innerHeight) || (bottom > 0 && bottom <= innerHeight))
&& ((left >= 0 && left < innerWidth) || (right > 0 && right <= innerWidth));
// dom横穿window或者竖穿或者dom包裹window
// 横穿
const case2 = (left <= 0 && right > 0 && right >= innerWidth)
&& ((top >= 0 && top < innerHeight) || (bottom > 0 && bottom <= innerHeight));
// 竖穿
const case3 = (top <= 0 && bottom > 0 && bottom >= innerHeight)
&& ((left >= 0 && left < innerWidth) || (right > 0 && right <= innerWidth));
// dom包裹window
const case4 = (left <= 0 && right > 0 && right >= innerWidth)
&& ((top <= 0) && (bottom > 0 && bottom >= innerHeight));
// 设置为true 即部分可见即算是可见
const partVisible = case1 || case2 || case3 || case4;
// 设置为false 即有一部份不可见即不可见
const allVisible = top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
return partiallyVisible ? partVisible : allVisible;
};
【JS】判断Dom是否在可视区
最新推荐文章于 2025-05-21 18:02:04 发布