gpt4 book ai didi

javascript - 如果在 css 中设置为 0px,如何根据内容计算像素高度?

转载 作者:行者123 更新时间:2023-11-28 05:18:23 26 4
gpt4 key购买 nike

我给了一个元素 0px 的高度,如下所示

#sample{
height: 0px;
overflow: hidden;
transition-duration: 1.2s;
}

<div id="sample">
<h1>Hello World main headinh</h1>
<h2>Hello World sub heading</h2>
<p>Hello world paragraph</p>
</div>

如果我没有指定高度,那么它将采用内容的高度(比如 50 像素)。现在开始我不知道 #sample 的高度。我想将它的高度设置为其原始计算高度(即 50px),我可以通过指定高度 100% 来实现。

document.getElementById("sample").style.height = "100%";

但是 transition-duration 属性在那种情况下不起作用,所以当我将百分比更改为像素时,transition-duration 属性运行良好。

document.getElementById("sample").style.height = "50px";

但这里的问题是 div 中的内容是动态的,所以它的高度也在变化。

那么我怎样才能为 #sample 提供内容所需的高度(以像素为单位)。解决方案应该只有 Javascript 而不是任何其他框架,如 JQuery

最佳答案

试试这个。

var element = document.getElementById('sample');
element.style.height= element.scrollHeight+"px"

https://jsfiddle.net/y0g22540/

关于javascript - 如果在 css 中设置为 0px,如何根据内容计算像素高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42230344/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com