2015-04-22 44 views
0

我已阅读https://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/但仍不确定如何配置以实现我的目标。如何用突变观察者通过Id隐藏元素

代码生成器生成的页面上有一个元素(所以我不能防止这种情况)。元素有一个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();

回答

1

为什么不你只需使用CSS?这样你就不用担心物品何时被创建,你不需要一开始就有脚本。

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