美文网首页
MutationObserver - 2020-08-18

MutationObserver - 2020-08-18

作者: 勇敢的小拽马 | 来源:发表于2020-08-18 17:03 被阅读0次

官方使用方式示例

//选择一个需要观察的节点
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();

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

示例引用链接 https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

相关文章

网友评论

      本文标题:MutationObserver - 2020-08-18

      本文链接:https://www.haomeiwen.com/subject/sgekjktx.html