美文网首页
JavaScript监视对DOM树所做的更改

JavaScript监视对DOM树所做的更改

作者: 段煜华 | 来源:发表于2020-04-19 12:48 被阅读0次
// 选择将观察突变的节点
var targetNode = document.getElementById('some-id');

// 观察者的选择(观察哪些突变)
var config = { attributes: true, childList: true, subtree: true };

// 当观察到突变时执行的回调函数
var callback = function(mutationsList) {
    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.');
        }
    }
};

// 创建一个链接到回调函数的观察者实例
var observer = new MutationObserver(callback);

// 开始观察已配置的突变的目标节点
observer.observe(targetNode, config);

// 停止观察
observer.disconnect();
浏览器兼容

相关文章

网友评论

      本文标题:JavaScript监视对DOM树所做的更改

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