IntersectionObserver的使用

225 阅读1分钟

功能

监听目标元素与祖先元素(默认是根元素)的交叉情况

使用

const intersectionObserver = new IntersectionObserver((entries) => {
    // entries.forEach(i => {
    //     if (i.isIntersecting) {
    //         console.log(i)
    //     }
    // })
    console.log(entries)
}, {
    root: document.getElementsByClassName("box")[0],
    rootMargin:"10px 10px",
    threshold:[0,0.5]
})
  • root:指定祖先元素,没有指定时默认为根元素
  • rootMargin:指定观察区域的扩展大小或收缩大小,定义格式类似margin
    • 默认观察区域为祖先元素的大小
  • threshold:指定交叉比例,当元素与root交叉比例等于threshold时,触发回调函数

entries常使用的属性

  • isIntersecting:当前元素与root交叉是否满足threshold,是返回true,否返回false
  • target:监听的目标元素

例子

监听元素是否进入父级元素

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 300px;
            height: 300px;
            background: mediumaquamarine;
            position: relative;
        }

        .box1 {
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
            left: 350px;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="box1"></div>
    </div>
    <script>
        const box = document.getElementsByClassName("box")[0]
        const box1 = document.getElementsByClassName("box1")[0]
        const intersectionObserver = new IntersectionObserver((entries) => {
            entries.forEach(i => {
                if (i.isIntersecting) {
                    console.log(i)
                }
            })
        }, {
            root: box,
            threshold: 0.01
        })
        intersectionObserver.observe(box1)
        setInterval(() => {
            box1.style.left = box1.offsetLeft - 20 + 'px'
        }, 1000);
    </script>
</body>

</html>