简体   繁体   English

JavaScript getBoundingClientRect()vs offsetHeight,同时计算元素高度

[英]JavaScript getBoundingClientRect() vs offsetHeight while calculate element height

What is the best way to get element height: 获得元素高度的最佳方法是什么:

var myElement = document.querySelector('.some-class');

var height = myElement.getBoundingClientRect().height;

or 要么

var myElement = document.querySelector('.some-class');

var height = myElement.offsetHeight;  

Most of the time these are the same as width and height of getBoundingClientRect() , when there aren't any transforms applied to the element. 大多数情况下,当没有任何变换应用于元素时,这些与getBoundingClientRect()的宽度和高度相同。 In case of transforms, the offsetWidth and offsetHeight returns the element's layout width and height, while getBoundingClientRect() returns the rendering width and height. 在转换的情况下,offsetWidth和offsetHeight返回元素的布局宽度和高度,而getBoundingClientRect()返回渲染宽度和高度。 As an example, if the element has width: 100px; 例如,如果元素的宽度为:100px; and transform: scale(0.5); 和变换:规模(0.5); the getBoundingClientRect() will return 50 as the width, while offsetWidth will return 100. getBoundingClientRect()将返回50作为宽度,而offsetWidth将返回100。

https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Det​​ermining_the_dimensions_of_elements

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM