【问题标题】:Chrome MutationObserver not activated on some elementsChrome MutationObserver 未在某些元素上激活
【发布时间】:2018-01-07 21:46:04
【问题描述】:

我遇到了一个问题,即 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 修改和更改)
还有一些是白色的,因为它们具有在类中定义的背景(即帖子正文)

但是顶部的菜单条(包含标题/本地/等)也会变成白色。

如果我检查我发现它现在有

<div class="gb_wd gb_Wd" style="background-color: rgb(255, 255, 255);">

所以它改变了它的风格(背景颜色从红色变为白色)但没有被突变观察者“捕捉”。

这是一个错误吗?还是我做错了什么?如何让 MutationObserver 观察这些变化?

谢谢!

【问题讨论】:

    标签: javascript google-chrome mutation-observers


    【解决方案1】:

    属性突变,比如style,不加节点所以需要重新着色mutation.target

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      • 2021-12-27
      • 2013-06-04
      • 2018-04-30
      • 1970-01-01
      • 2020-07-16
      相关资源
      最近更新 更多