简体   繁体   中英

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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