使用 mutationObserver 定位特定元素

target specific element with mutationObserver

我正在使用 mutationObserver 通过波纹管代码检测变化

var target = document.querySelector('body');

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });    
});

var config = { attributes: true, childList: true, characterData: true };
observer.observe(target, config);

在这里,如果目标元素内部发生变化,我现在能够检测到变化,我正在瞄准 body

我真正想要的是 mutationObserver 事件仅在我指定的元素添加到 DOM

时触发

您可以在此页面上找到一个很好的 Mutation Observer 示例:

http://www.htmlgoodies.com/beyond/javascript/respond-to-dom-changes-with-mutation-observers.html

工作示例在主体上添加观察者,如果您添加、删除或更改属性,您可以捕获更改。

但是要确保所有的东西都被很好地捕获,请使用这个 observerConfig。

            var observerConfig = {
                    attributes: true,
                    childList: true,
                    characterData: true,
                    subtree : true
            };