ResizeObserver 是否最初在页面加载时调用?

chz*_*zzh 6 javascript dom observers

似乎当我在 DOMContentLoaded 事件上将节点传递给 ResizeObserver.observe() 时,它会立即调用。这是否被视为正常行为?

Kai*_*ido 6

是的,这种行为是根据规范(参考):

  • 当被观察的元素从 DOM 中插入/移除时,观察将触发。

  • 当观察元素显示设置为无时,观察将触发。

  • Observations do not fire for non-replaced inline Elements.

  • Observations will not be triggered by CSS transforms.

  • Observation will fire when observation starts if Element is being rendered, and Element’s size is not 0,0.

So in your case, either the element was not yet in the DOM and case 1 will make it fire, either it was already, and case 5 will (though in DOMContentLoaded, that should be 5 ;).

  • @phil294,如果调整大小事件侦听器函数根据观察到的元素的大小设置某种状态,那么您可能希望初始化该状态,即使观察到的元素实际上并没有立即更改其大小。 (2认同)