JavaScript getBoundingClientRect()与offsetHeight,同时计算元素高度 [英] JavaScript getBoundingClientRect() vs offsetHeight while calculate element height

查看:71
本文介绍了JavaScript getBoundingClientRect()与offsetHeight,同时计算元素高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取元素高度的最佳方法是什么?

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.

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

这篇关于JavaScript getBoundingClientRect()与offsetHeight,同时计算元素高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆