elemento con l'altezza massima da un insieme di elementi


85

Ho una serie di divelementi. In jQuery, vorrei essere in grado di scoprire divl'altezza massima e anche l'altezza di quella div. Per esempio:

<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>

Guardando quanto sopra, sappiamo che il 2 ° div(con 4 linee) ha l'altezza massima di tutti. Come lo scopro? Qualcuno potrebbe aiutare per favore?

Finora ho provato:

$("div.panel").height()che restituisce l'altezza del 1 ° div.

Risposte:


213

Usa .map()e Math.max.

var maxHeight = Math.max.apply(null, $("div.panel").map(function ()
{
    return $(this).height();
}).get());

Se è difficile leggere, questo potrebbe essere più chiaro:

var heights = $("div.panel").map(function ()
    {
        return $(this).height();
    }).get();

maxHeight = Math.max.apply(null, heights);

1
Questo trova l'altezza più alta ma non un riferimento all'elemento reale.
Vincent Ramdhanie

Hai ragione; Non era chiaro se anche l'OP volesse l'elemento. La tua risposta funziona in questo caso.
Matt Ball

3
@ MattBall Perché la funzione get, posso chiedere? Cosa fa e qual è il suo scopo?
chodorowicz

2
@chodorowicz contento che hai chiesto. Vedi questa risposta , sotto il secondo titolo.
Matt Ball

1
@ MattBall Thanks. Quindi jQuery .map restituisce un oggetto simile ad un array e get .get lo trasforma in array. Ma sembra che Math.max funzioni facilmente su entrambi questi tipi (appena testato nella console Chrome), quindi in questo caso .get non sembra necessario. O mi sbaglio?
chodorowicz

20

L'html che hai pubblicato dovrebbe usarne alcuni <br>per avere effettivamente div con altezze diverse. Come questo:

<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>

A parte questo, se vuoi un riferimento al div con l'altezza massima puoi farlo:

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");

Fai attenzione con questo, se non usi un metodo jQuery all'interno (come .heightin questo caso), devi dereferenziarlo, ad esempio: `$ (this) [0] .scrollHeight;`
rogerdpack

5

Se vuoi riutilizzare in più posti:

var maxHeight = function(elems){
    return Math.max.apply(null, elems.map(function ()
    {
        return $(this).height();
    }).get());
}

Quindi puoi usare:

maxHeight($("some selector"));

1

function startListHeight($tag) {
  
    function setHeight(s) {
        var max = 0;
        s.each(function() {
            var h = $(this).height();
            max = Math.max(max, h);
        }).height('').height(max);
    }
  
    $(window).on('ready load resize', setHeight($tag));
}

jQuery(function($) {
    $('#list-lines').each(function() {
        startListHeight($('li', this));
    });
});
#list-lines {
    margin: 0;
    padding: 0;
}

#list-lines li {
    float: left;
    display: table;
    width: 33.3334%;
    list-style-type: none;
}

#list-lines li img {
    width: 100%;
    height: auto;
}

#list-lines::after {
    content: "";
    display: block;
    clear: both;
    overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<ul id="list-lines">
    <li>
        <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="" />
        <br /> Line 1
        <br /> Line 2
    </li>
    <li>
        <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="" />
        <br /> Line 1
        <br /> Line 2
        <br /> Line 3
        <br /> Line 4
    </li>
    <li>
        <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="" />
        <br /> Line 1
    </li>
    <li>
        <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="" />
        <br /> Line 1
        <br /> Line 2
    </li>
</ul>


1

ul, li {
  list-style: none;
  margin: 0;
  padding: 0;
}

ul {
  display: flex;
  flex-wrap: wrap;
}

ul li {
  width: calc(100% / 3);
}

img {
  width: 100%;
  height: auto;
}
<ul>
  <li>
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="">
    <br> Line 1
    <br> Line 2
  </li>
  <li>
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="">
    <br> Line 1
    <br> Line 2
    <br> Line 3
    <br> Line 4
  </li>
  <li>
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="">
    <br> Line 1
  </li>
  <li>
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="">
    <br> Line 1
    <br> Line 2
  </li>
</ul>



0

Se eri interessato all'ordinamento interamente in JavaScript standard o senza utilizzare forEach ():

var panels = document.querySelectorAll("div.panel");

// You'll need to slice the node_list before using .map()
var heights = Array.prototype.slice.call(panels).map(function (panel) {
    // return an array to hold the item and its value
    return [panel, panel.offsetHeight];
}),

// Returns a sorted array
var sortedHeights = heights.sort(function(a, b) { return a[1] > b[1]});

0

Il modo più semplice e chiaro che direi è:

var maxHeight = 0, maxHeightElement = null;
$('.panel').each(function(){
   if ($(this).height() > maxHeight) {
       maxHeight = $(this).height();
       maxHeightElement = $(this);
   }
});

0

Questo potrebbe essere utile, in qualche modo. Correzione di un codice da @diogo

$(window).on('load',function(){

// get the maxHeight using innerHeight() function
  var maxHeight = Math.max.apply(null, $("div.panel").map(function ()                                                        {
    return $(this).innerHeight();
  }).get());
  
// Set the height to all .panel elements
  $("div.panel").height( maxHeight );
  
});
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.