首页 > 解决方案 > 如何使用 ResizeObserver 仅检查 JavaScript 中正文的宽度变化?

问题描述

我想检查<body>的宽度变化(不是高度)。

有没有办法用 ResizeObserver 做到这一点?

标签: javascriptresize-observer

解决方案


这是一个例子。在https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver阅读更多文档。

function handleWidthChange (width) {
  console.log(width);
}

let prevWidth = 0;

const observer = new ResizeObserver(entries => {
  for (const entry of entries) {
    const width = entry.borderBoxSize?.[0].inlineSize;
    if (typeof width === 'number' && width !== prevWidth) {
      prevWidth = width;
      handleWidthChange(width);
    }
  }
});

observer.observe(document.body, {box: 'border-box'});

推荐阅读