前端做吸附、懒加载、返回顶部、自定义 tooltip,全都依赖「元素在哪、有多大」。浏览器给了一组名字相近的属性,差别就在「算不算边框、算不算滚动、是不是整数」。
宽度三兄弟
clientWidth= width + padding,不含边框、不含滚动条。offsetWidth= width + padding + border,含边框,含滚动条占的宽度。getBoundingClientRect().width= 实际渲染宽度,含 transform 缩放,可能是小数。
所以「元素看起来多宽」应该用 getBoundingClientRect;「布局占位多宽」用 offsetWidth;「内容能放多宽」用 clientWidth。
位置怎么算
offsetLeft / offsetTop 是相对最近的定位祖先(position 非 static),没有定位祖先则相对初始包含块。要算到视口,需要逐级累加:
function offsetToViewport(el) {
let left = 0, top = 0
while (el) { left += el.offsetLeft; top += el.offsetTop; el = el.offsetParent }
return { left, top }
}
// 更省事的写法:
const r = el.getBoundingClientRect()
const x = r.left + window.scrollX, y = r.top + window.scrollY
滚动相关
scrollTop / scrollLeft:元素已滚动的距离,可读写。- 页面滚动距离:
document.documentElement.scrollTop(标准模式),写的时候建议用window.scrollY兜底。 scrollWidth / scrollHeight:内容实际尺寸,常用于判断「是否还有更多」。
事件与性能
scroll 和 resize 触发非常频繁,回调里不要做重活。读取尺寸会强制同步布局(layout thrashing),所以「先读完所有尺寸,再统一写入」比读写交替快得多。
window.addEventListener('scroll', () => {
// 用 rAF 合并到下一帧,回调里只做计算,不写样式
requestAnimationFrame(update)
}, { passive: true })