How to calculate height of div in jQuery?

2020-07-20 04:20发布

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-height in it. I know we can calculate height of div by :

$("#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.

I hope I explained it clearly.

Thanks

4条回答
淡お忘
2楼-- · 2020-07-20 05:00

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

查看更多
姐就是有狂的资本
3楼-- · 2020-07-20 05:06

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.

$('#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.

查看更多
We Are One
4楼-- · 2020-07-20 05:14

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/

查看更多
趁早两清
5楼-- · 2020-07-20 05:22

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/

and if your html is:

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

then you can use this to get the height:

$("#parent").css('height'); // this will give you the 450px
查看更多
登录 后发表回答