【问题标题】:MutationObserver for new created element?新创建元素的 MutationObserver?
【发布时间】:2021-05-19 16:55:53
【问题描述】:

如何对新创建的元素进行 MutationObserver?当我创建一个新元素时,mutatonObserver 不起作用。如果巨盒换了样式,我需要注册...

<button onclick="myFunction()">Create</button>
<button onclick="myFunctionStyle()">Change style</button>
var observerm = new MutationObserver(function(mutationsm) {
    mutationsm.forEach(function(mutationRecord) {
        alert('style changed!');
    });    
});

var targetm = document.getElementById("Box");
observerm.observe(targetm, { attributes : true, attributeFilter : ['style'] });


function myFunction() {
  var newdiv = document.createElement("DIV");
  newdiv.innerHTML = "Box";
  newdiv.id = "Box";
  newdiv.style.width = "100px";
  newdiv.style.height = "50px";
  newdiv.style.backgroundColor = "red";
  
  document.body.appendChild(newdiv);
}

function myFunctionStyle() {
  document.getElementById("Box").style.backgroundColor = "blue";
}

【问题讨论】:

    标签: javascript dom styles mutation-observers


    【解决方案1】:

    由于新添加的元素已附加到document.body,因此您需要将另一个 MutationObserver 附加到该元素。

    new MutationObserver(() => {
      console.log('mutation on document body');
      // rest of the code you need when an element is appended
    })
      .observe(document.body, { childList: true })
    

    【讨论】:

    • 一切正常,但如果创建了一个新元素,只是mutationObserver不会注册它
    • 如果该元素从未被附加,检测它的唯一方法是覆盖并修补document 上的createElement 方法。如果你不知道 where 它将被附加,但它会被附加到某个地方,你可以这样做,或者在 childList 属性之外附加一个带有 subtree: true 的递归观察者。
    • 在本例中,我在 document.body 中指定了 create 元素,但我需要在其他已创建元素中使用它。 div inside div ...,inside div ...,我正在尝试您的解释,但它不再起作用
    • 最好的解决方案是识别您感兴趣的每个容器并在每个容器上附加一个观察者,childList: true
    • 我明白你的意思,但是每个父母也是被创造出来的……所以……嗯
    猜你喜欢
    • 2015-11-26
    • 2020-07-16
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 2019-08-12
    相关资源
    最近更新 更多