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
2 Answers
Reset to default 13As 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
版权声明:本文标题:javascript - How to react to a specific style attribute change with mutation observers? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740277872a2253272.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论