如何判断元素是否在可视区

223 阅读1分钟

1、IntersectionObserver

异步观察目标元素与其祖先元素或顶级文档视窗是否交叉,可以监听多个

使用方法

const intersectionObserver = new IntersectionObserver(function(entries){
    entries.forEach(entry=>{
        if(entry.isIntersecting){
            // 交叉
            ...
        }else{
            // 不交叉
            ...
        }
    })
})

intersectionObserver.observe(targetElement1)
intersectionObserver.observe(targetElement2)

注意

  1. 可以通过记录entry.time,计算元素曝光时长

2、getBoundingClientRect

返回元素的大小及其相对于视口的位置

使用方法

const { bottom, height, left, right, top, width, x, y } = targetElement.getBoundingClientRect()

function isElementInViewport (el) {
    var rect = el.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && 
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) 
    );
}

注意

  1. left:元素左边界距窗口最左边的距离
    right:元素右边界距窗口最左边的距离
    top:元素上边界距窗口最上面的距离
    bottom:元素下边界距窗口最上面的距离
  2. 需要监听scroll变化,实时获取位置信息

参考

github.com/zuopf769/no…

developer.mozilla.org/zh-CN/docs/…