MutationObserver
接口提供了监视对DOM树所做更改的能力。它被设计为旧的Mutation Events功能的替代品,该功能是DOM3 Events规范的一部分。
构造函数
-
MutationObserver()
-
创建并返回一个新的
MutationObserver
它会在指定的DOM发生变化时被调用。
方法
-
disconnect()
-
阻止 MutationObserver
实例继续接收的通知,直到再次调用其observe()
方法,该观察者对象包含的回调函数都不会再被调用。 -
observe()
-
配置
MutationObserver
在DOM更改匹配给定选项时,通过其回调函数开始接收通知。 -
takeRecords()
-
从MutationObserver的通知队列中删除所有待处理的通知,并将它们返回到
MutationRecord
对象的新Array
中。
示例
以下示例改编自这篇博客。
// Select the node that will be observed for mutations var targetNode = document.getElementById('some-id'); // Options for the observer (which mutations to observe) var config = { attributes: true, childList: true, subtree: true }; // Callback function to execute when mutations are observed 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.'); } } }; // Create an observer instance linked to the callback function var observer = new MutationObserver(callback); // Start observing the target node for configured mutations observer.observe(targetNode, config); // Later, you can stop observing observer.disconnect(); // ES-next version // Select the node that will be observed for mutations let targetNode = document.querySelector(`#id`); // Options for the observer (which mutations to observe) let config = { attributes: true, childList: true, subtree: true }; // Callback function to execute when mutations are observed const mutationCallback = (mutationsList) => { for(let mutation of mutationsList) { let type = mutation.type; switch (type) { case "childList": console.log("A child node has been added or removed."); break; case "attributes": console.log(`The ${mutation.attributeName} attribute was modified.`); break; case "subtree": console.log(`The subtree was modified.`); break; default: break; } } }; // Create an observer instance linked to the callback function let observer = new MutationObserver(mutationCallback); // Start observing the target node for configured mutations observer.observe(targetNode, config); // Later, you can stop observing observer.disconnect();
转自https://developer.mozilla.org/zh-CN/docs/Web/API/MutationObserver