获取元素的宽度和高度

要获取元素的宽度和高度,可以使用元素的 offsetWidthoffsetHeight 属性

const box = document.querySelector('.box');

const width = box.offsetWidth,
    height = box.offsetHeight;Code language: JavaScript (javascript)

offsetWidthoffsetHeight 包括填充和边框。

要获取不带边框的元素的宽度和高度,可以使用 clientWidthclientHeight 属性

const box = document.querySelector('.box');

const width = box.clientWidth,
    height = box.clientHeight;Code language: JavaScript (javascript)

请注意,clientWidthclientHeight 属性也包括填充。

本教程是否有帮助?