在 JavaScript 中,我们经常需要获取和操作 DOM 元素的大小和滚动位置。以下是关于这些操作的核心属性和方法:
offsetWidth / offsetHeight - 元素的总宽度/高度,包括边框、内边距和滚动条(如果有)offsetLeft / offsetTop - 元素相对于最近定位祖先元素的左/上偏移量offsetParent - 最近的定位祖先元素clientWidth / clientHeight - 元素的内部宽度/高度,包括内边距但不包括边框、滚动条和外边距clientLeft / clientTop - 左边框/上边框的宽度(通常等于边框宽度)scrollWidth / scrollHeight - 元素内容的完整宽度/高度,包括由于溢出而不可见的部分scrollLeft / scrollTop - 元素内容向左/向上滚动的像素数(可读写)// 视口尺寸
const viewportWidth = window.innerWidth || document.documentElement.clientWidth;
const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
// 整个文档的尺寸
const docWidth = Math.max(
document.body.scrollWidth, document.documentElement.scrollWidth,
document.body.offsetWidth, document.documentElement.offsetWidth,
document.body.clientWidth, document.documentElement.clientWidth
);
const docHeight = Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight,
document.body.offsetHeight, document.documentElement.offsetHeight,
document.body.clientHeight, document.documentElement.clientHeight
);
// 获取滚动位置
const scrollX = window.pageXOffset || document.documentElement.scrollLeft;
const scrollY = window.pageYOffset || document.documentElement.scrollTop;
const rect = element.getBoundingClientRect();
// 返回一个对象,包含相对于视口的精确位置和尺寸:
// {
// x, y, // 左上角坐标
// left, top, // 同上
// right, // 右边界X坐标
// bottom, // 下边界Y坐标
// width, // 元素的宽度
// height // 元素的高度
// }
// 滚动到特定位置
window.scrollTo(x, y);
window.scrollTo({
top: 100,
left: 0,
behavior: 'smooth' // 平滑滚动
});
// 滚动元素使其可见
element.scrollIntoView();
element.scrollIntoView({ behavior: 'smooth', block: 'center' });
// 获取/设置元素的滚动位置
const scrollLeft = element.scrollLeft;
element.scrollTop = 200;
getBoundingClientRect() 和 IntersectionObserver API 来替代部分传统方法这些属性和方法为 JavaScript 提供了强大的能力来检测和操作页面元素的尺寸和滚动行为。
热门推荐:
0