2012-11-10 12 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...> 

Jak używać jQuery znaleźć najkrótszą div?Jak znaleźć najkrótszą div z JQuery

Na przykład powyższy wynik dałby id div = "c3", ponieważ jego wysokość wynosi 90 pikseli.

Odpowiedz

0

Oto jak to zrobić bez 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

Użyj metody jQuery .height(), która zwraca obliczoną wartość wysokości dla danego elementu.

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

Czy naprawdę chcesz najmniejszy? A może chciałeś tego z najmniejszą wysokością? To są różne rzeczy. Oto rozwiązanie, które wyszukuje najmniejszy obszar po obszarze (ale można go pokonać wysokością, zastępując $(this).height() * $(this).width() przez $(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; 
}); 
Powiązane problemy