代码之家  ›  专栏  ›  技术社区  ›  kofifus

Chrome MutationObserver在某些元素上未激活

  •  3
  • kofifus  · 技术社区  · 7 年前

    我遇到了一个问题,MutationObserver在某些元素上无法工作。

    在chrome load 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();
    

    它的作用是:

    • 首先将所有元素背景更改为红色

    现在更改标题(即,单击业务)

    结果是,您得到了一些红色的元素(未修改)



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

    如果我检查,我看到它现在已经

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

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

    谢谢!

    1 回复  |  直到 7 年前
        1
  •  1
  •   woxxom    7 年前

    属性突变,例如 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';
        }
      }
    }