我有一套div元素.在jQuery,我希望能够找到div最大高度和高度div.例如:
<div>
<div class="panel">
Line 1
Line 2
</div>
<div class="panel">
Line 1<br/>
Line 2<br/>
Line 3<br/>
Line 4<br/>
</div>
<div class="panel">
Line 1
</div>
<div class="panel">
Line 1
Line 2
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
通过观察上面的内容,我们知道第二个div(有4条线)具有所有的最大高度.我怎么找到这个?有人可以帮忙吗?
到目前为止,我已经尝试过:
$("div.panel").height()返回第1个高度div.
Mat*_*all 201
var maxHeight = Math.max.apply(null, $("div.panel").map(function ()
{
return $(this).height();
}).get());
Run Code Online (Sandbox Code Playgroud)
如果这令人困惑,那么这可能会更清楚:
var heights = $("div.panel").map(function ()
{
return $(this).height();
}).get();
maxHeight = Math.max.apply(null, heights);
Run Code Online (Sandbox Code Playgroud)
Vin*_*nie 19
您发布的HTML应该使用一些<br>实际上具有不同高度的div.像这样:
<div>
<div class="panel">
Line 1<br>
Line 2
</div>
<div class="panel">
Line 1<br>
Line 2<br>
Line 3<br>
Line 4
</div>
<div class="panel">
Line 1
</div>
<div class="panel">
Line 1<br>
Line 2
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
除此之外,如果你想要一个具有最大高度的div的引用,你可以这样做:
var highest = null;
var hi = 0;
$(".panel").each(function(){
var h = $(this).height();
if(h > hi){
hi = h;
highest = $(this);
}
});
//highest now contains the div with the highest so lets highlight it
highest.css("background-color", "red");
Run Code Online (Sandbox Code Playgroud)
如果要在多个地方重复使用:
var maxHeight = function(elems){
return Math.max.apply(null, elems.map(function ()
{
return $(this).height();
}).get());
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用:
maxHeight($("some selector"));
Run Code Online (Sandbox Code Playgroud)