elemento con la altura máxima de un conjunto de elementos


85

Tengo un conjunto de divelementos. En jQuery, me gustaría poder averiguar divcon la altura máxima y también la altura de eso div. Por ejemplo:

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

Al mirar lo anterior, sabemos que la 2da div(con 4 líneas) tiene la altura máxima de todas. ¿Cómo averiguo esto? ¿Podría alguien ayudarme?

Hasta ahora lo he intentado:

$("div.panel").height()que devuelve la altura del 1er div.

Respuestas:


213

Utilice .map()y Math.max.

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

Si resulta confuso de leer, esto podría ser más claro:

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

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

1
Esto encuentra la altura más alta pero no una referencia al elemento real.
Vincent Ramdhanie

Tienes razón; No estaba claro si el OP también quiere el elemento. Tu respuesta funciona en ese caso.
Matt Ball

3
@MattBall ¿Por qué la función get, puedo preguntar? ¿Qué hace y cuál es su propósito?
chodorowicz

2
@chodorowicz me alegro de que lo hayas preguntado. Vea esta respuesta , bajo el segundo encabezado.
Matt Ball

1
@MattBall Gracias. Entonces, jQuery .map devuelve un objeto similar a una matriz y get .get lo convierte en una matriz. Pero parece que Math.max funciona fácilmente en ambos tipos (recién probado en la consola de Chrome), por lo que en este caso .get parece innecesario. ¿O me equivoco?
chodorowicz

20

El html que publicó debería usar algo <br>para tener divs con diferentes alturas. Me gusta esto:

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

Aparte de eso, si desea una referencia al div con la altura máxima, puede hacer esto:

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

Tenga cuidado con este, si no usa un método jQuery dentro (como .heighten este caso), entonces debe eliminar la referencia, por ejemplo: `$ (this) [0] .scrollHeight;`
rogerdpack

5

Si desea reutilizar en varios lugares:

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

Entonces puedes usar:

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

Si estaba interesado en ordenar completamente en JavaScript estándar, o sin usar 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

La forma más fácil y clara que yo diría es:

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

0

Esto podría ser útil, de alguna manera. Arreglando un código de @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 );
  
});
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.