如何检索 HTML 元素的实际宽度和高度? [英] How do I retrieve an HTML element's actual width and height?
问题描述
假设我有一个 <div>
我希望在浏览器的显示(视口)中居中.为此,我需要计算
我应该用什么?请提供有关浏览器兼容性的信息.
你应该使用 .offsetWidth
和 .offsetHeight
属性.注意它们属于元素,而不是 .style
.
var width = document.getElementById('foo').offsetWidth;
函数.getBoundingClientRect()
在执行 CSS 转换后以浮点数形式返回元素的尺寸和位置.
>console.log(document.getElementById('id').getBoundingClientRect())DOM矩形{底部:177,身高:54.7,左:278.5,右:909.5,顶部:122.3,宽度:631,x: 278.5,y:122.3,}
Suppose that I have a <div>
that I wish to center in the browser's display (viewport). To do so, I need to calculate the width and height of the <div>
element.
What should I use? Please include information on browser compatibility.
You should use the .offsetWidth
and .offsetHeight
properties.
Note they belong to the element, not .style
.
var width = document.getElementById('foo').offsetWidth;
Function .getBoundingClientRect()
returns dimensions and location of element as floating-point numbers after performing CSS transforms.
> console.log(document.getElementById('id').getBoundingClientRect())
DOMRect {
bottom: 177,
height: 54.7,
left: 278.5,
right: 909.5,
top: 122.3,
width: 631,
x: 278.5,
y: 122.3,
}
这篇关于如何检索 HTML 元素的实际宽度和高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!