我可以使用MutationObserver来监听计算样式的变化吗? [英] Can I use a MutationObserver to listen for changes on computed styles?

查看:1124
本文介绍了我可以使用MutationObserver来监听计算样式的变化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用MutationObserver来监听计算样式的变化吗?我有一个宽度为100%的div,我想知道它的计算宽度是否变化,但到目前为止还没有成功。如果我改变了实际的风格,MutationObserver可以工作:

Can I use a MutationObserver to listen for changes on computed styles? I have a div which width is 100% and I'd like to know when its computed width changes, but so far no success. The MutationObserver works if I change the style pragmatically:

document.getElementById(myDiv)。style.width =200px

但是如果界面通过调整窗口大小调整大小,或者如果父div调整大小,则不起作用。

But it doesn't work if the interface is resized by a window resize or if a parent div resizes.

任何不涉及超时的解决方案?

Any solution that doesn't involve timeouts?

更新:我特别感兴趣的一个解决方案,也不会涉及听窗口调整大小事件,因为有时界面改变,而窗口大小调整。例如,具有百分比宽度和父节点大小的div会更改。

UPDATE: I'm particularly interested in a solution that also wouldn't involve listening to window resize event, because sometimes the interface changes without the window resizing. For instance, a div that has a percentage as width and a parent node size changes.

推荐答案

支持观察样式更改为<讨论中的href =http://xml3d.org/xml3d/specification/styleobserver/ =noreferrer> 。现在你可以利用转换。这个想法是为元素的width(或任何)添加一个css转换。过渡期应该有几乎为零的时间,所以你不会注意到。

Support for observing style changes is in discussion. For now you could leverage transitions. The idea is to add a css transition for the width (or whatever) to the element. The transition should have a duration of almost zero, so you won't notice it.

转换完成后,$ code> transitionend 事件触发。添加该事件的监听器。现在每当宽度变化时,转换将开始,立即完成,事件将触发。这意味着你的听众将被调用。

After a transition has finished a transitionend event is fired. Add a listener for that event. Now whenever the width changes, the transition will start, immediately finish and the event will fire. Which means your listener will be called.

#myDiv {
  ...
  transition: width 0.01s;
}

$("#myDiv").on("transitionend", function () { ... } );

由IE10 +

这篇关于我可以使用MutationObserver来监听计算样式的变化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆