问题描述
获取元素高度的最佳方法是什么?
What is the best way to get element height:
var myElement = document.querySelector('.some-class');
var height = myElement.getBoundingClientRect().height;
或
var myElement = document.querySelector('.some-class');
var height = myElement.offsetHeight;
推荐答案
大多数情况下,当未应用任何转换时,这些宽度与 getBoundingClientRect()的宽度和高度相同元素.如果进行转换,则offsetWidth和 offsetHeight 返回元素的布局宽度和高度,而 getBoundingClientRect()返回渲染的宽度和高度.例如,如果元素的宽度为:100px;并转换:scale(0.5); getBoundingClientRect()将返回50作为宽度,而offsetWidth将返回100.
Most of the time these are the same as width and height of getBoundingClientRect(), when there aren't any transforms applied to the element. In case of transforms, the offsetWidth and offsetHeight returns the element's layout width and height, while getBoundingClientRect() returns the rendering width and height. As an example, if the element has width: 100px; and transform: scale(0.5); the getBoundingClientRect() will return 50 as the width, while offsetWidth will return 100.
这篇关于JavaScript getBoundingClientRect()与offsetHeight,同时计算元素高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!