简体   繁体   English

如何使用突变观察器按ID隐藏元素

[英]How to hide an element by Id with mutation observer

I've read https://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/ but still not sure how to configure to achieve my objective. 我已阅读https://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/,但仍不确定如何配置以实现我的目标。

There's an element on a page being generated by a code generator (so I cannot prevent the bevahiour). 页面上有一个由代码生成器生成的元素(因此我无法避免这种行为)。 The element has an id "myid" and I just need to hide it once it displays in the browser. 元素的ID为“ myid”,一旦在浏览器中显示,我只需将其隐藏。 My challenge is how to configure the observer such that the code fires when the element is displayed. 我的挑战是如何配置观察者,以便在显示元素时触发代码。

I've inserted my questions as comments where I think I need the help here but kindly guide me if I've got it all wrong: 我已将我的问题作为评论插入,我想在这里需要我的帮助,但是如果我做错了的话,请指导我:

 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(); 

Why don't you simply use CSS? 您为什么不简单地使用CSS? That way you don't have to worry about when the item is created at all, you won't need a script do begin with. 这样,您完全不必担心什么时候创建项目,就不需要脚本开始了。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM