浏览器的5种Observer

IntersectionObserver

监听一个元素和可视区域相交部分的比例,然后再可视比例达到某个阀值的时候触发回调

<!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>
        #box1,
        #box2 {
            width: 100px;
            height: 100px;
            background: blue;
            color: #fff;
            position: relative;
        }

        #box1 {
            top: 500px;
        }

        #box2 {
            top: 800px;
        }
    </style>
</head>

<body>
    <div id="box1">BOX11</div>
    <div id="box2">BOX22</div>
    <script>
        // 监听一个元素和可视区域相交部分的比例,然后再可视比例达到某个阀值的时候触发回调
        const intersectionObserver = new IntersectionObserver(
            function (entries) {
                console.log('info')
                entries.forEach(item => {
                    console.log(item.target, item.intersectionRatio)
                })
            }, {
            threshold: [0.5, 1]
        }
        )
        intersectionObserver.observe(document.querySelector('#box1'))
        // intersectionObserver.observe(document.querySelector('#box2'))
    </script>
</body>

</html>

MutationObserver

监听对元素的属性的修改、对它的子节点的增删改

ResizeObserver

监听大小的改变,当 widthheight 被修改时会触发回调

PerformanceObserver

用于监听记录 performance 数据的行为,一旦记录了就会触发回调

ReportingObserver

监听过时的 api 、浏览器的一些干预行为的报告

参考

Last updated

Was this helpful?