簡體   English   中英

新創建元素的 MutationObserver?

[英]MutationObserver for new created element?

如何對新創建的元素進行 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";
}

由於新添加的元素已附加到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 })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM