如何使用突变观察者对特定的样式属性更改做出反应

How to react to a specific style attribute change with mutation observers?

本文关键字:属性 样式 突变 何使用 观察者      更新时间:2023-09-26

我一直在尝试使用突变观察者,到目前为止,我可以应用相关函数来对添加、删除元素等做出反应。现在我想知道,是否有一种方法可以针对特定样式属性中的特定更改?我知道我可以观察属性的变化,但我就是不知道如何观察特定的属性修改。例如,如果#childDiv的z-index值更改为5678,则修改parentDiv的样式以便显示它。

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

根据文档使用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);
    }
}

对不起。React是没有突变的。如果你需要听一些元素的变化(例如风格)。您可以使用componentDidUpdate并从@refs.parentDiv获得元素(在此之前在渲染函数<div id="parentDiv" ref="parentDiv" style="display:none;">中设置ref),然后检查样式并在新渲染之前设置z-Index值。