How to respond to a change in an attribute of a particular style using mutator observers?

I experimented with the Mutation Observer, while I can apply the appropriate functions to respond to adding, removing elements, etc. Now I'm wondering if there is a way to customize specific changes within a specific style attribute? I know that I can watch for changes to attributes, but I just don’t know how to watch for a particular modification of an attribute. For example, if the z-index value for #childDiv changes to 5678, change the parentDiv style so that it displays.

<div id="parentDiv" style="display:none;"> <div id="childDiv" style="z-index:1234;"> MyDiv </div> </div> 
+3
source share
2 answers

According to the documentation, use the attributeFilter array and list the HTML attributes, 'style' here:

 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); } } 
+6
source

Sorry for the offtopic. Recipe React No Mutation. If you need to listen to some changes of an element (for example, style). You can use componentDidUpdate and get the element from @refs.parentDiv (set ref before this in the rendering function <div id="parentDiv" ref="parentDiv" style="display:none;"> ) and after the validation style and set the value to z -Index before the new render.

+1
source

Source: https://habr.com/ru/post/1263987/


All Articles