繁体   English   中英

MutationObserver 观察风格变化只触发一次

[英]MutationObserver watching for style change only firing once

我有以下 div:

<div id="new-address-modal" style="display:none;"> </div>

使用在属性更改时触发的 MutationObserver(因此我需要它在样式属性更改时触发

var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutationRecord) {
    console.log('style changed!');
  });    
});

var target = document.getElementById('new-address-modal');
observer.observe(target, { attributes : true, attributeFilter : ['style'] });

但这只会被触发一次。 在初始触发后,我应该怎么做才能在样式改变时触发?

谢谢!

你所拥有的东西,你只是没有改变属性的样式,所以它永远不会被触发。

在这个例子中,我所做的就是每秒改变背景颜色。 突变观察者不会在元素的初始创建时触发,因此如果这是您所期望的,您将需要创建一个函数并在元素加载时触发它。

如果您将值从一件事修改为同一件事,这也永远不会触发该事件。

例如:

<!-- HTML -->
<div style="background: red"></div>

// JavaScript
target.style.background = 'red'

如您所见,它是红色的,我们正在尝试将其设置为红色。 突变不会触发,因为没有任何改变。

 var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutationRecord) { console.log('style changed!'); }); }); var target = document.getElementById('new-address-modal'); observer.observe(target, { attributes: true, attributeFilter: ['style'] }); // My only edits: setInterval(function(){ target.style.display = Math.floor(Math.random() * 2) == 0 ? 'none' : 'initial' }, 1000)
 <div id="new-address-modal" style="display:none;">Now you see me</div>

在示例中,您可以看到当值保持不变时,它永远不会被触发。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM