MutationObserver在样式更改时删除div

时间:2019-06-21 06:07:46

标签: javascript dom

我想在样式更改时删除div。我读过MutationObserver可以做到这一点。但是我尝试的代码无法正常工作。

const observer = new MutationObserver(function
(mutations) {
    mutations.forEach(function (mutation) {
        if (mutation.attributes === 'style') {
            removeDiv()
        }
    })
})

const elem = document.querySelector('.show-pl');
observer.observe(elem, {
    attributes: true
})

function removeDiv() {
    Object.assign(elem.style, {
        display: 'none',
    })
}

2 个答案:

答案 0 :(得分:0)

添加新元素与属性无关,并且您无法观察到不在DOM中的元素的突变。

相反,您会在父元素上寻找childList的修改,div将被添加到(或祖先的childList + subtree中(如果不能)直接监视父母-如有必要,祖先甚至可以是document.body)。

下面是直接看父母的例子:

// Set up the observer on the container
let observer = new MutationObserver(function() {
    // Does the div exist now?
    const div = document.querySelector(".show-pl");
    if (div) {
        // Yes, "remove" it (you're really just hiding it) and release this observer
        console.log("The div has appeared, hiding and releasing observer");
        div.style.display = "none";
        observer.disconnect();
        observer = null;
    }
});
observer.observe(document.getElementById("the-parent"), {
    childList: true
});
console.log("Watching for the element");

// On a delay, create the div
setTimeout(() => {
    console.log("Creating the div");
    const div = document.createElement("div");
    div.textContent = "Hi there!";
    div.className = "show-pl";
    document.getElementById("the-parent").appendChild(div);
}, 800);
<div id="the-parent"></div>

要观看祖先,您可以在observe调用中使用祖先,并将subtree: true添加到init选项中。

答案 1 :(得分:0)

function removeDiv(canvas) { 
    var elem = document.querySelector('.show-pl');
    elem.parentNode.removeChild(elem);
}

var observer = new MutationObserver(function (mutations, me) {
  var canvas = document.querySelector(".show-pl");
  if (canvas) {
    removeDiv(canvas);
    me.disconnect();
    return;
  }
});

observer.observe(document, {
  childList: true,
  subtree: true
});

这就是我想要的,但是会发生错误“无法读取null的属性'addeventlistener'”,因为div在DOM中尚不存在。

相关问题