如何通过变异观察者对特定样式属性的变化做出反应?

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

我一直在试验 Mutation Observers,到目前为止,我可以应用相关函数对添加、删除元素等做出反应。现在我想知道,有没有办法针对特定样式属性中的特定更改?我知道我可以观察属性变化,但我只是不知道如何观察特定的属性修改。例如,如果#childDiv 的 z-index 值更改为 5678,请修改 parentDiv 的样式以使其显示。

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

根据 the documentation 使用 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);
    }
}

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