如何使用突变观察者通过 Id 隐藏元素



我已经阅读了 https://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/但仍然不确定如何配置以实现我的目标。

页面上有一个元素是由代码生成器生成的(所以我无法阻止 bevahiour)。该元素有一个 id "myid",我只需要在浏览器中显示后将其隐藏即可。我的挑战是如何配置观察器,以便在显示元素时触发代码。

我已经将我的问题作为评论插入到我认为我需要帮助的地方,但如果我弄错了,请指导我:

var target = document.querySelector('#myid');
 
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
  // how do I detect when the element is now on the page so that the next statement makes sense?
    document.getElementById("myid").style.visibility = "hidden";     
  });    
});
 
// what change do I need to make here?
var config = { attributes: true, childList: true, characterData: true }; 
 
observer.observe(target, config);
 
observer.disconnect();

为什么不简单地使用 CSS?这样,您就不必担心何时创建项目,也不需要脚本开始。

#myid {
  visibility: hidden; /*!important; if necessary*/
}

最新更新