探索MutationObserver

59 阅读1分钟

MutationObserver 是一个可以监听DOM结构变化的接口。

官方示例

首先我们先来看看官方示例:

    //选择一个需要观察的节点
    var targetNode = document.getElementById('some-id');

    // 设置observer的配置选项
    var config = { attributes: true, childList: true, subtree: true };

    // 当节点发生变化时的需要执行的函数
    var callback = function(mutationsList, observer) {
        for(var mutation of mutationsList) {
            if (mutation.type == 'childList') {
                console.log('A child node has been added or removed.');
            }
            else if (mutation.type == 'attributes') {
                console.log('The ' + mutation.attributeName + ' attribute was modified.');
            }
        }
    };

    // 创建一个observer示例与回调函数相关联
    var observer = new MutationObserver(callback);

    //使用配置文件对目标节点进行观测
    observer.observe(targetNode, config);

    // 停止观测
    observer.disconnect();

示例引用链接

使用方式详解

    <!DOCTYPE html>

    <div id="opop">
        <div class="op"></div>
        <div class="op"></div>
        <div class="op op-node-change"></div>
    </div>
    <!--引用jqery-->
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
    <script>

        var targetNode =document.getElementById('opop');

        var observer = new MutationObserver(function(mutations) {
            var $node = $('#opop .op:not(.op-node-change)');
            $node.addClass('op-node-change test');
            console.log(111111);
        });

        observer.observe(targetNode, { attributes: true, childList: true, subtree: true });

    </script>

上述代码是一个简单的应用示例, 是在id="opop"下,给所有的没有"op-node-change"的div 增加类"op-node-change test"

这段代码直接运行后的显示为:

10060876-41f9e0f5268c1e35.webp

很奇怪,这里可以看到div的类名并没有发生改变。代码有问题?

此时,在Console中动态的增加新的节点

10060876-d483b0546889400d.webp

然后再次查看Dom节点

10060876-99423afe129c58fc.webp

可以看到div 的类名发生了我们所期待的变化。

这是因为MutationObserver是监听DOM树变化的接口,一开始的时候后div先加载,然后是js加载,此时DOM树没有发生变化,所有MutationObserver的回调函数没有执行,当我们动态的改变DOM树的结构时,MutationObserver监听到了变化,所以回调函数起了作用。这就是我们最后看到的结果。