如何对突变观察者对特定样式属性更改做出反应? [英] How to react to a specific style attribute change with mutation observers?
问题描述
我一直在试验Mutation Observers,到目前为止,我可以应用相关的功能来添加,删除元素等做出反应。现在我想知道,有没有一种方法来针对特定的风格属性中的具体变化?我知道我可以观察属性的变化,但我只是不知道如何观察一个特定的属性修改。例如,如果#childDiv的z-index值更改为5678,请修改parentDiv的样式以使其显示。
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>
推荐答案
根据文档使用 attributeFilter
数组并列出HTML属性,'style'
这里:
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);
}
}
这篇关于如何对突变观察者对特定样式属性更改做出反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!