2015-04-22 50 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*/ 
}