要获取元素的宽度和高度,可以使用元素的 offsetWidth
和 offsetHeight
属性
const box = document.querySelector('.box');
const width = box.offsetWidth,
height = box.offsetHeight;
Code language: JavaScript (javascript)
offsetWidth
和 offsetHeight
包括填充和边框。
要获取不带边框的元素的宽度和高度,可以使用 clientWidth
和 clientHeight
属性
const box = document.querySelector('.box');
const width = box.clientWidth,
height = box.clientHeight;
Code language: JavaScript (javascript)
请注意,clientWidth
和 clientHeight
属性也包括填充。
本教程是否有帮助?