Javascript 某些元素上未激活Chrome MutationObserver
我遇到了一个问题,MutationObserver无法处理某些元素 我提取了一个“简单”的例子: 在chrome加载news.google.com并打开调试器控制台 粘贴此代码:Javascript 某些元素上未激活Chrome MutationObserver,javascript,google-chrome,mutation-observers,Javascript,Google Chrome,Mutation Observers,我遇到了一个问题,MutationObserver无法处理某些元素 我提取了一个“简单”的例子: 在chrome加载news.google.com并打开调试器控制台 粘贴此代码: for (elem of document.getElementsByTagName('*')) elem.style.backgroundColor = 'red'; let observer; function mutationObserve() { observer.observe(document,
for (elem of document.getElementsByTagName('*')) elem.style.backgroundColor = 'red';
let observer;
function mutationObserve() {
observer.observe(document, { childList: true, subtree:true, attributes: true });
}
function mutationDisconnect() {
observer.disconnect();
}
function handleMutation(mutations) {
mutationDisconnect();
mutations.forEach(mutation => {
for (elem of mutation.addedNodes) {
elem.style.backgroundColor = 'green';
for (innerElem of elem.getElementsByTagName('*')) {
innerElem.style.backgroundColor = 'green';
}
}
});
mutationObserve();
}
observer = new MutationObserver(handleMutation);
mutationObserve();
它的作用是:
- 首先将所有元素背景更改为红色
- 设置一个变异观察者,将所有修改元素的背景更改为绿色
和一些绿色元素(由MutationObserver修改和更改)
有些是白色的,因为它们的背景是在类中定义的(即,post body)
但是顶部的菜单条(包含标题/local/etc)也会变成白色 如果我检查,我看到它现在已经
<div class="gb_wd gb_Wd" style="background-color: rgb(255, 255, 255);">
因此它改变了它的风格(背景颜色从红色变为白色),但没有被突变观察者“捕捉”
这是虫子吗?还是我做错了什么?我如何让MutationObserver观察这些变化
谢谢 属性突变,如
样式
,不添加节点,因此需要重新调用突变。目标
:
for (const mutation of mutations) {
if (mutation.type == 'attributes')
mutation.target.style.backgroundColor = 'yellow';
for (const elem of mutation.addedNodes) {
if (elem.nodeType != Node.ELEMENT_NODE)
continue;
elem.style.backgroundColor = 'green';
for (const innerElem of elem.getElementsByTagName('*')) {
innerElem.style.backgroundColor = 'green';
}
}
}