【发布时间】: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