MutationObserver 接口提供了监视对 DOM 树所做更改的能力。MDN:https://developer.mozilla.org/zh-CN/docs/Web/API/MutationObserver
// 选择需要观察变动的节点const targetNode = document.getElementById('some-id');// 观察器的配置(需要观察什么变动)const config = { attributes: true, childList: true, subtree: true };// 当观察到变动时执行的回调函数const callback = function(mutationsList, observer) {// Use traditional 'for loops' for IE 11for(let 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.');}}};// 创建一个观察器实例并传入回调函数const observer = new MutationObserver(callback);// 以上述配置开始观察目标节点observer.observe(targetNode, config);// 之后,可停止观察observer.disconnect();
