You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ResizeObserverEntry.contentRect属性值为0或不正确的问题排查

解决ResizeObserver contentRect定位偏差问题

你踩了个常见的坑:ResizeObserver返回的contentRect和getBoundingClientRect的坐标体系完全不一样。

contentRect里的left/top/x/y是元素内容区域相对于自身padding盒的偏移量(通常都是0,除非元素有内边距或者滚动),而不是相对于视口的坐标。这就是为什么你看到left/top是0,right/bottom刚好等于元素宽高——因为right = left + width,bottom = top + height。

而绝对定位的元素设置left/top时,是相对于最近的定位父元素(没有的话就是视口),所以必须用视口坐标才能正确覆盖目标元素。

直接改回调里的逻辑,用目标元素的getBoundingClientRect()获取正确的视口坐标就行:

const button = document.getElementById('button');
const div = document.getElementById('div');

const observer = new ResizeObserver(entries => {
  // 直接获取元素相对于视口的坐标
  const boundingRect = button.getBoundingClientRect();
  console.log(boundingRect.x, boundingRect.y, boundingRect.top, boundingRect.left);

  div.style.left = boundingRect.left + "px";
  div.style.top = boundingRect.top + "px";
  div.style.width = boundingRect.width + "px";
  div.style.height = boundingRect.height + "px";
});
observer.observe(button);

对应的CSS和HTML可以保持不变,这样div就能精准覆盖button了。

另外补充一点:如果你的页面有滚动,getBoundingClientRect()返回的坐标会随滚动变化,要是需要相对于文档的坐标,得加上window.scrollX和window.scrollY。

内容的提问来源于stack exchange,提问作者luek baja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 04:18:13