Jquery计算div的最小所需高度值

时间:2022-04-13 16:01:41

Currently i am setting absolute height values. But sometimes i am being have to set a lot higher than required because of dynamic pages. Is it possible to get minimum required height of div ? i mean the height value which will show all the elements like height auto but no empty spaces will left. I can't set height auto because it causes too much mess. I tried and failed.

目前我正在设置绝对高度值。但有时由于动态页面,我必须设置比要求高很多。是否有可能获得最低所需的div高度?我的意思是高度值,它将显示所有元素,如高度自动,但不会留下空白空间。我无法设置高度自动,因为它会导致太多混乱。我尝试过但失败了。

So jquery will read the div and calculate minimum required height value for displaying all elements. Is this possible ?

因此jquery将读取div并计算显示所有元素所需的最小高度值。这可能吗 ?

Thank you.

2 个解决方案

#1


4  

As Clive said, there is usually no reason to do this. However, if you need to get height of all inside elements, you can use something like this:

正如克莱夫所说,通常没有理由这样做。但是,如果你需要获得所有内部元素的高度,你可以使用这样的东西:

var height = 0;
$.each($("your_div").children(), function(i,v) {
    height += $(v).outerHeight(true);
});
console.log(height);

Function outerHeight(true) counts height of the element including border and margin. See http://api.jquery.com/outerHeight/ for details.

函数outerHeight(true)计算元素的高度,包括边框和边距。有关详细信息,请参见http://api.jquery.com/outerHeight/。

#2


2  

You can also wrap the elements inside another div.

您还可以将元素包装在另一个div中。

<div class="toResize">
    <div>
        <element1 />
        <element2 />
    </div>
</div>

Then, only resize the outer-most div (.toResize). If you need the minimum height, you can get it via

然后,只调整最外层的div(.toResize)。如果您需要最小高度,您可以通过它获得

var minHeight = $(".toResize").children("div").height();

I hope that helps.

我希望有所帮助。

#1


4  

As Clive said, there is usually no reason to do this. However, if you need to get height of all inside elements, you can use something like this:

正如克莱夫所说,通常没有理由这样做。但是,如果你需要获得所有内部元素的高度,你可以使用这样的东西:

var height = 0;
$.each($("your_div").children(), function(i,v) {
    height += $(v).outerHeight(true);
});
console.log(height);

Function outerHeight(true) counts height of the element including border and margin. See http://api.jquery.com/outerHeight/ for details.

函数outerHeight(true)计算元素的高度,包括边框和边距。有关详细信息,请参见http://api.jquery.com/outerHeight/。

#2


2  

You can also wrap the elements inside another div.

您还可以将元素包装在另一个div中。

<div class="toResize">
    <div>
        <element1 />
        <element2 />
    </div>
</div>

Then, only resize the outer-most div (.toResize). If you need the minimum height, you can get it via

然后,只调整最外层的div(.toResize)。如果您需要最小高度,您可以通过它获得

var minHeight = $(".toResize").children("div").height();

I hope that helps.

我希望有所帮助。