摘要:在本教程中,您将学习如何获取元素的当前计算尺寸,包括宽度和高度。
下图显示了 CSS 盒模型,其中包含一个带有内容、填充、边框和边距的块元素
要获取元素的宽度和高度,包括填充和边框,请使用元素的 offsetWidth 和 offsetHeight 属性
let box = document.querySelector('.box');
let width = box.offsetWidth;
let height = box.offsetHeight;Code language: JavaScript (javascript)下图说明了元素的 offsetWidth 和 offsetHeight
请参阅以下示例
let box = document.querySelector('.box');
let width = box.offsetWidth;
let height = box.offsetHeight;
console.log({ width, height });
Code language: HTML, XML (xml)输出
{width: 122, height: 172}Code language: JavaScript (javascript)在此示例中
宽度为 100px边框在每侧为 1px,因此两侧为 2px。填充在每侧为 10px,因此两侧为 20px。因此,总宽度为 122px。类似地,总高度为 172px。
要获取经过 CSS 变换后元素的宽度和高度(以浮点数形式),请使用 DOM 元素的 getBoundingClientRect() 方法。例如
let box = document.querySelector('.box');
let width = box.offsetWidth;
let height = box.offsetHeight;
console.log({ width, height });
const domRect = box.getBoundingClientRect();
console.log(domRect);
Code language: HTML, XML (xml)输出
{width: 122, height: 172}
DOMRect {x: 7.997685432434082, y: 7.997685432434082, width: 121.95602416992188, height: 171.95602416992188, top: 7.997685432434082, …}Code language: JavaScript (javascript)clientWidth & clientHeight要获取元素的宽度和高度,包括填充但不包括边框,请使用 clientWidth 和 clientHeight 属性
let box = document.querySelector('.box');
let width = box.clientWidth;
let height = box.clientHeight;Code language: JavaScript (javascript)下图说明了元素的 clientWidth 和 clientHeight
要获取元素的边距,请使用 getComputedStyle() 方法
let box = document.querySelector('.box');
let style = getComputedStyle(box);
let marginLeft = parseInt(style.marginLeft);
let marginRight = parseInt(style.marginRight);
let marginTop = parseInt(style.marginTop);
let marginBottom = parseInt(style.marginBottom);Code language: JavaScript (javascript)要获取元素的边框宽度,请使用 getComputedStyle() 方法返回的 style 对象的属性
let box = document.querySelector('.box');
let style = getComputedStyle(box);
let borderTopWidth = parseInt(style.borderTopWidth) || 0;
let borderLeftWidth = parseInt(style.borderLeftWidth) || 0;
let borderBottomWidth = parseInt(style.borderBottomWidth) || 0;
let borderRightWidth = parseInt(style.borderRightWidth) || 0;Code language: JavaScript (javascript)要获取窗口的高度和宽度,请使用以下代码
let width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
let height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;Code language: JavaScript (javascript)摘要使用 DOM 元素的 offsetWidth 和 offsetHeight 属性来获取其宽度和高度。测验 本教程是否有用? 是 否 发送 取消
