简体   繁体   English

如何根据内容获取 HTML 元素的高度?

[英]How to get an HTML element's height according to its content?

I have a react App with a component including a div to have a long text.我有一个带有组件的反应应用程序,其中包含一个 div 以获得长文本。 I have a "Show description" button to expand this long text div.我有一个“显示说明”按钮来展开这个长文本 div。 So, in the beginning, I set the div height to 0px and when I click on the Show description button, the div needs to be fully expanded with some animations.因此,一开始,我将 div 高度设置为 0px,当我单击 Show description 按钮时,需要使用一些动画完全展开 div。 The problem is, even though I set the initial height as 0px, I'm not sure how to set the expanded height according to the content.问题是,即使我将初始高度设置为 0px,我也不知道如何根据内容设置展开高度。 Here is what I tried,这是我尝试过的,

descriptionExpanded = (expanded) => {
    this.setState({ descriptionExpanded: expanded })
}

<div style={{ height: descriptionExpanded ? `60px` : '0px', transition: descriptionExpanded ? 'height 0.25s ease-in' : 'height 0.15s ease-out' }}>
    Long text...
</div>
<div onClick={() => this.descriptionExpanded(!descriptionExpanded)}>
    <span>{descriptionExpanded ? 'Hide Description' : 'Show Description'}</span>
</div>

I need to set this "60px" to a variable value which is the actual height of the div with the whole text.我需要将此“60px”设置为一个变量值,该值是 div 与整个文本的实际高度。 When I'm tried with "auto" instead "60px" and "100%": "0%" instead of pixels, the show/hide switch is not working.当我尝试使用"auto"而不是"60px""100%": "0%"而不是像素时,显示/隐藏开关不起作用。 And when I'm tried with "100%": "0px" , the switch is working but without animations.当我尝试使用"100%": "0px" ,开关正在工作但没有动画。 I think the animation is working only for pixels.我认为动画仅适用于像素。

How can I do this to work properly?我怎样才能做到这一点才能正常工作?

one method to get the hight and weight of an element is as bellow:获取元素高度和重量的一种方法如下:

 var clientHeight = document.getElementById('element_id').clientHeight;
 var clientWidth = document.getElementById('element_id').clientWidth;

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

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