javascript 如何在jQuery中计算div的高度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14097994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:42:41  来源:igfitidea点击:

How to calculate height of div in jQuery?

javascriptjquery

提问by Ravinder Singh

I am in such a situation that I have to set height of a div depends on the amount of content in it, I can't give min-heightin it. I know we can calculate height of div by :

我处于这样一种情况,我必须设置 div 的高度取决于其中的内容量,我不能放弃min-height。我知道我们可以通过以下方式计算 div 的高度:

$("#divid").height();

So is there any way we can calculate height of a div without having height parameter in it and give height to that div depends on the amount of content in it.

那么有什么方法可以在没有高度参数的情况下计算 div 的高度,并根据其中的内容量赋予该 div 的高度。

I hope I explained it clearly.

我希望我解释清楚。

Thanks

谢谢

采纳答案by Travis J

Just like you said, with .height(), there does not need to be an actual height defined for that to be used. here is a jsfiddle showing it in action: http://jsfiddle.net/nWb5j/

就像您说的那样,使用.height(),不需要为要使用的高度定义实际高度。这是一个 jsfiddle,显示它在行动:http: //jsfiddle.net/nWb5j/

回答by loganfsmyth

Your wording is a bit confusing, but I think you are asking how to calculate the size of the content inside a div even if the div has a different height applied. For that you can use the element's scrollHeight.

您的措辞有点令人困惑,但我认为您是在问如何计算 div 内内容的大小,即使 div 应用了不同的高度。为此,您可以使用元素的scrollHeight

$('#divid')[0].scrollHeight

If you just want to know how to calculate the height of an element even though it has no attribute/style for height, you can just use what you have written in the question. .height()computes the height of the element directly from the browser rendered values, not from the attributes specifically.

如果您只想知道如何计算元素的高度,即使它没有高度的属性/样式,您可以使用您在问题中所写的内容。.height()直接从浏览器呈现的值计算元素的高度,而不是专门从属性计算。

回答by Jai

You have two ways doing it:

你有两种方法:

$("#parent").height($("#child").outerHeight(true));
//-----------------------------^^^^^^^^^^^--^^^^-----outerHeight(true) will give
//---------------------------------------------------you the total height 
//---------------------------------------------------including top bottom margins

more info .outerHeight : http://api.jquery.com/outerHeight/

更多信息 .outerHeight :http://api.jquery.com/outerHeight/

and if your html is:

如果您的 html 是:

<div style="height:450px;"></div>

then you can use this to get the height:

那么你可以使用它来获取高度:

$("#parent").css('height'); // this will give you the 450px

回答by Joseph

jQuery calculates the height, using .height(), even when there is no height setting (via CSS or otherwise) on the element.

.height()即使元素上没有设置高度(通过 CSS 或其他方式),jQuery也会使用 来计算高度