在 jQuery 中选择 DIV 的真实高度
我有一个定义了固定高度的 DIV:
.w {
height: 100px;
overflow: hidden;
}
如果我将文本放入其中,它将隐藏超出 100 像素的所有内容。我有一个显示所有文本的按钮,基本上它是这样做的:
$('.w').height('auto');
这将使所有文本可见,但我想为其设置动画。这不适用于 height='auto',它必须有一个特定的高度。
问题:如何获得 DIV 应该能够显示其中所有文本的高度?
I have a DIV defined with a fixed height:
.w {
height: 100px;
overflow: hidden;
}
if I put text in this it will hide everything that goes beyond the 100px. I have a button that shows all text, basically it does this:
$('.w').height('auto');
this will make all text visible, but I would like to animate this. And that won't work with height='auto', it has to have a specific height.
The question: how do I get the height the DIV should be to be able to show all text in it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试像这样的
scrollHeight
:注意
[0]
,因为它是 DOM 元素的属性。try
scrollHeight
like this:Note
[0]
, as it is property of DOM elements.您可以将高度设置为“自动”,然后测量它,然后将其设置回来并启动效果。
像这样的东西(现场示例):
You could set the height to 'auto', then measure it, then set it back and start the effect.
Something like this (live example):
TJ Crowder 的答案对我不起作用,因为“oldHeight”是计算出的像素值,与我在样式表中指定的 rem 值不同。此外,内联样式覆盖了我为另一个媒体查询设置的不同高度。因此,我没有保存“oldHeight”并稍后将其放回去,而是通过将 css 'height' 设置为空字符串来清除 jQuery 的内联样式。
T.J. Crowder's answer didn't work for me because "oldHeight" was a calculated pixel value, different than the rem value I had specified in my stylesheet. Also, the inline style overrode a different height I had for another media query. So, instead of saving the "oldHeight" and putting it back later, I just cleared jQuery's inline style by setting css 'height' to an empty string.