Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/google-chrome/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 某些元素上未激活Chrome MutationObserver_Javascript_Google Chrome_Mutation Observers - Fatal编程技术网

Javascript 某些元素上未激活Chrome MutationObserver

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,

我遇到了一个问题,MutationObserver无法处理某些元素

我提取了一个“简单”的例子:

在chrome加载news.google.com并打开调试器控制台

粘贴此代码:

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';
    }
  }
}