2012-11-10 23 views
6
<div id="c1" class="features" style="height:100px;width:100px;"></div> 
<div id="c2" class="features" style="height:120px;width:100px;"></div> 
<div id="c3" class="features" style="height:90px;width:100px;"></div> 
<div...> 

如何使用JQuery找到最短的div如何用JQuery找到最短的div

例如,以上將導致div id =「c3」,因爲它的高度是90px。

回答

0

這裏是如何做到這一點沒有 JQuery的:

var allDivs = document.getElementsByTagName("div"); 

var min = 0; 
var element; 

for (var i = 0; i < allDivs.length; i++) { 
    if (allDivs[i].className == "features") { 
     if (allDivs[i].offsetHeight < min) { 
      min = allDivs[i].offsetHeight; 
      element = allDivs[i]; 
     } 
    } 
} 

alert(element); 
0

使用jQuery的.height()方法,它返回一個元素的計算高度值。

var candidates = getSetOfDivs(); 
var smallest = candidates[0]; 
$(candidates).each(function(e, i) { 
    if($(e).height() > smallest.height()) smallest = $(e); 
}); 
0

你真的想要最小嗎?或者你只是想要一個最小的高度?那些是不同的東西。這是一個解決方案,可以找到最小的一個區域(但您可以通過將$(this).height() * $(this).width()替換爲$(this).height()來實現高度化)。

var divs = $('.features'); 

var smallest; 
var smallestarea = null; 

$('.features').each(function() { 
    var thisarea = $(this).height() * $(this).width(); 
    if (smallestarea === null || thisarea < smallestarea) { 
    smallest = $(this); 
    smallestarea = thisarea; 
    } 
}); 

document.write(smallest.attr('id')); 

http://jsbin.com/ufujiy/1/edit

9
var shortest = [].reduce.call($(".features"), function(sml, cur) { 
    return $(sml).height() < $(cur).height() ? sml : cur; 
});