实现说明
顶层就这几处状态:box、rect、measured。
使用要点
- 用到了
document,需要在浏览器环境运行,Node 里直接跑会缺 API。 - 跑完文件,输出里会留下标记——
x/y:、width includes padding+border:、height:。
常见问题
「getBoundingClientRect 测量渲染盒」能在裸 Node.js 里跑吗?
不能——document 的家在浏览器里,Node 进程提供不了。执行时请用页面(或 DevTools 控制台)。
核心语句
const measured = box.getBoundingClientRect().width;
const box = document.createElement('div');
const rect = box.getBoundingClientRect();
代码示例
// 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);