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

Come utilizzare JQuery per trovare il più breve div?Come trovare il div più breve con JQuery

Ad esempio, quanto sopra risulterebbe in div id = "c3" perché la sua altezza è 90px.

risposta

0

Ecco come farlo senza 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

Utilizzare il metodo jQuery .height(), che restituisce il valore di altezza calcolato per un elemento.

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

Volevi davvero il più piccolo? O vuoi solo quello con la minima altezza? Quelle sono cose diverse. Ecco una soluzione che trova il più piccolo per area (ma potresti aumentare di altezza sostituendo $(this).height() * $(this).width() con $(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; 
}); 
Problemi correlati