如何对新创建的元素进行MutationObserver?当我创建一个新元素时,mutationObserver不起作用。如果这个巨大的盒子改变了样式,我需要注册。。。
<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 })