admin管理员组

文章数量:1247209

I've been experimenting with Mutation Observers, so far I can apply the relevant functions to react upon adding, removing elements and so on. Now I am wondering, is there a way to target a specific change within a specific style attribute? I know I can observe for attribute changes, but I just don't know how to observe for a specific attribute modification. For example, if the z-index value of #childDiv changes to 5678, modify the style of the parentDiv in order for it to be shown.

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

I've been experimenting with Mutation Observers, so far I can apply the relevant functions to react upon adding, removing elements and so on. Now I am wondering, is there a way to target a specific change within a specific style attribute? I know I can observe for attribute changes, but I just don't know how to observe for a specific attribute modification. For example, if the z-index value of #childDiv changes to 5678, modify the style of the parentDiv in order for it to be shown.

<div id="parentDiv" style="display:none;">
  <div id="childDiv" style="z-index:1234;">
    MyDiv
  </div>
</div>
Share Improve this question edited Aug 18, 2016 at 17:54 JMZ asked Aug 18, 2016 at 17:26 JMZJMZ 1452 silver badges10 bronze badges 1
  • 1 There seems to be an attributeFilter option you can pass in to find a specific attribute. Obviously it will trigger for any change inside of the style attribute, because the value is not special to the MutationObserver. – Heretic Monkey Commented Aug 18, 2016 at 17:34
Add a ment  | 

2 Answers 2

Reset to default 13

As per the documentation use 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);
    }
}

Sorry for offtop. Conception React is no mutations. If you need to listen some changes of some element (style for example). You can use ponentDidUpdate and get element from @refs.parentDiv (set ref before this in render function <div id="parentDiv" ref="parentDiv" style="display:none;">) and after check style and set you z-Index value before new render.

本文标签: javascriptHow to react to a specific style attribute change with mutation observersStack Overflow