![](/img/trans.png)
[英]Access delay to children after a MutationObserver on a created element in the DOM
[英]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.