ResizeObserver Tracks Element Box Changes

Observe an element's content box with ResizeObserver instead of window resize events, writing measurements to data attributes and toggling classes.

JavascriptData Fetching

Code

javascriptsnippet
17 lines
// ResizeObserver: 观察元素盒尺寸变化,而不是 window resize 事件
function observePanels(panels) {
  const observer = new ResizeObserver((entries) => {
    for (const entry of entries) {
      const box = entry.contentBoxSize[0];
      // 写回 data-* 属性,供 CSS 或调试读取
      entry.target.dataset.inlineSize = String(Math.round(box.inlineSize));
      entry.target.classList.toggle('narrow', box.inlineSize < 320);
    }
  });
  panels.forEach((panel) => observer.observe(panel));
  return observer;
}

// 页面卸载或列表重渲染时断开,避免观察已移除的节点
const observer = observePanels(document.querySelectorAll('.panel'));
observer.disconnect();

How it works

ResizeObserver Tracks Element Box Changes keeps everything in the function observePanels.

Iteration happens inside for (const entry of entries) — everything outside it runs once.

Caveats

  • The snippet leans on document, ResizeObserver — browser-only surfaces a bare Node process cannot provide.

Applying it

The main signature reads function observePanels(panels)

Statements that matter

panels.forEach((panel) => observer.observe(panel));
const observer = new ResizeObserver((entries) => {
  for (const entry of entries) {
    const box = entry.contentBoxSize[0];
    // 写回 data-* 属性,供 CSS 或调试读取
    entry.target.dataset.inlineSize = String(Math.round(box.inlineSize));
    entry.target.classList.toggle('narrow', box.inlineSize < 320);
  }
});

Interactive Tools for This Topic

FAQ

Does ResizeObserver Tracks Element Box Changes run in plain Node.js?
No — it touches `document` and `ResizeObserver`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.