探索awesome-open-source-flutter-apps中的AI与生成式应用:15款创新工具全解析
2026/5/6 16:15:32
getBoundingClientRect()是 JavaScript 中一个非常重要的DOM API,用于获取元素在视口(viewport)中的位置和尺寸信息。
const rect = element.getBoundingClientRect();
返回一个DOMRect对象,包含以下只读属性(单位:像素):
| 属性 | 含义 |
|---|---|
x/left | 元素左边缘到视口左侧的距离 |
y/top | 元素上边缘到视口顶部的距离 |
right | 元素右边缘到视口左侧的距离 |
bottom | 元素下边缘到视口顶部的距离 |
width | 元素宽度(等价于right - left) |
height | 元素高度(等价于bottom - top) |
💡 注意:
x和left是等价的,y和top也是等价的(现代浏览器支持x/y)。
视口顶部 │ │ top (y) │ ↓ ├───────────────┐ ← left (x) │ │ │ 元素 │ → right │ │ └───────────────┘ │ │ bottom ↓ 视口底部假设你有一个很长的网页,其中有一个按钮:
<!-- 页面顶部 --> <h1>欢迎来到我的网站</h1> <!-- 中间有很多内容(比如 2000px 高的空白) --> <div style="height: 2000px; background: #eee;"></div> <!-- 目标按钮:距离页面顶部 2100px --> <button id="myBtn">点击我</button>top = 2100px(从页面最顶端算起)800px<h1>)const btn = document.getElementById('myBtn'); console.log(btn.getBoundingClientRect().top); // 输出:2100✅ 因为视口顶部就是页面顶部,所以top = 2100(按钮在视口下方 2100px)
console.log(btn.getBoundingClientRect().top); // 输出:600❓ 为什么变成600?
因为:
2100px1500px处2100 - 1500 = 600px✅
getBoundingClientRect().top始终告诉你:“这个元素现在离你眼前屏幕顶部有多远”
getBoundingClientRect()的坐标系原点是当前可见屏幕的左上角(视口),不是整个网页的左上角。js
编辑
const rect = el.getBoundingClientRect(); const absoluteTop = rect.top + window.scrollY; const absoluteLeft = rect.left + window.scrollX;