2016-08-18 59 views
1

我一直在試驗Mutation Observers,到目前爲止我可以應用相關函數來添加,刪除元素等等。現在我想知道,是否有一種方法可以針對特定樣式屬性中的特定更改?我知道我可以觀察屬性更改,但我不知道如何觀察特定的屬性修改。例如,如果#childDiv的z-index值更改爲5678,請修改parentDiv的樣式以使其顯示。如何使用突變觀察者對特定樣式屬性更改作出反應?

<div id="parentDiv" style="display:none;"> 
    <div id="childDiv" style="z-index:1234;"> 
    MyDiv 
    </div> 
</div> 
+1

似乎有一個'attributeFilter'選項可以傳入以查找特定屬性。顯然,它會觸發style屬性內部的任何更改,因爲該值對於MutationObserver不是特殊的。 –

回答

4

the documentation使用attributeFilter陣列並列出HTML屬性,'style'這裏:

var observer = new MutationObserver(styleChangedCallback); 
observer.observe(document.getElementById('childDiv'), { 
    attributes: true, 
    attributeFilter: ['style'], 
}); 

var oldIndex = document.getElementById('childDiv').style.zIndex; 

function styleChangedCallback(mutations) { 
    var newIndex = mutations[0].target.style.zIndex; 
    if (newIndex !== oldIndex) { 
     console.log('new:', , 'old:', oldIndex); 
    } 
} 
1

對不起offtop。 概念反應沒有突變。如果你需要聽某些元素的變化(例如風格)。您可以使用componentDidUpdate並從@refs.parentDiv(在渲染函數<div id="parentDiv" ref="parentDiv" style="display:none;">之前設置ref)和檢查樣式之後獲取元素,並在新渲染之前設置z-Index值。

+1

+1好的建議。打破這些反模式並獲得反應。那麼你可以真正學習一次,並寫在任何地方。祝你好運,上帝保佑 –