getBoundingClientRect Measures Rendered Boxes

getBoundingClientRect returns the rendered box in viewport coordinates including padding and border, the primitive for tooltips and droppables.

JavascriptData Integrity

Code

javascriptsnippet
23 lines
// getBoundingClientRect 返回元素在视口坐标系的渲染盒(含边框)
const box = document.createElement('div');
box.style.position = 'fixed';
box.style.left = '40px';
box.style.top = '60px';
box.style.width = '120px';
box.style.height = '48px';
box.style.padding = '8px';
box.style.border = '2px solid black';
document.body.append(box);

const rect = box.getBoundingClientRect();
console.log('x/y:', rect.x, rect.y);
console.log('width includes padding+border:', rect.width);
console.log('height:', rect.height);

// top 是视口坐标:普通文档流元素随滚动变化,本示例用 position: fixed 就是为了让坐标在滚动下保持稳定
console.log('top in viewport:', rect.top);

// 批量读取一次、再统一写入:读写交错会强制多次重排
const measured = box.getBoundingClientRect().width;
box.style.width = '200px';
console.log('measured before write:', measured);

Inside the snippet

Top-level bindings box, rect, measured hold the demo state — nothing sits inside a function scope.

What to watch for

  • document exist only in browsers — a Node runtime has no shims for them out of the box.

Putting it to use

The run emits 5 labeled sections — x/y:, width includes padding+border:, height:, top in viewport:, measured before write: — one per step.

Core lines

const measured = box.getBoundingClientRect().width;
const box = document.createElement('div');
const rect = box.getBoundingClientRect();

Interactive Tools for This Topic

FAQ

Does getBoundingClientRect Measures Rendered Boxes run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.