¿Cómo mantengo múltiples DIV a la misma altura usando jQuery?
Pregunta
Tengo algunas etiquetas DIV con diferentes cantidades de contenido de texto.
HTML:
<div id="boxes">
<div id="boxone">
<p>...</p>
</div>
<div id="boxtwo">
<p>...</p>
</div>
<div id="boxthree">
<p>...</p>
</div>
<div id="boxfour">
<p>...</p>
</div>
</div>
Están en un diseño de dos por dos y su ancho es fluido:
CSS:
div#boxes {
width: 100%;
}
div#boxes div {
width: 49.9%;
float: left;
}
Los quiero a todos a la misma altura.
Entonces, los recorro y encuentro la altura del más alto. Luego vuelvo a hacer un bucle y los establezco a esa altura.
jQuery:
$(function() {
var maxHeight = 0;
$('div#boxes div').each(function(){
if (maxHeight < $(this).height()) {maxHeight = $(this).height()}
});
$('div#boxes div').each(function(){
$(this).height(maxHeight);
});
});
Esto funciona bien si la altura del div no necesita cambiar nuevamente.
Pero falla si cambio el tamaño de la ventana del navegador:
-
Si (a) amplío el navegador, entonces (b) mi Los DIV se ensanchan, luego (c) su texto el contenido se ajusta menos veces y luego (d) mis DIV son demasiado altos.
-
Si (b) hago el navegador más estrecho, luego (b) mis DIV se vuelven más estrechos, luego (c) su contenido de texto envuelve más, y entonces (d) mis DIV son demasiado cortos.
¿Cómo ambos (1) dimensionamos automáticamente los DIV a la altura de su contenido de manera normal, pero también (2) mantengo esos múltiples DIV a la misma altura?
Solución
Actualizar ... reescribiendo completamente esta respuesta después de experimentar y encontrar otra forma aparentemente viable de hacer esto:
function sortNumber(a,b) {
return a - b;
}
function maxHeight() {
var heights = new Array();
$('div#boxes div').each(function(){
$(this).css('height', 'auto');
heights.push($(this).height());
heights = heights.sort(sortNumber).reverse();
$(this).css('height', heights[0]);
});
}
$(document).ready(function() {
maxHeight();
})
$(window).resize(maxHeight);
Una cosa que noté es que IE realmente tiene problemas de redondeo con divisiones flotantes de 50% de ancho ... la representación fue mucho mejor si las cambiara a 49%.
Este jQuery funciona ...
// global variables
doAdjust = true;
previousWidth = 0;
// raise doAdjust flag every time the window width changes
$(window).resize(function() {
var currentWidth = $(window).width();
if (previousWidth != currentWidth) {
doAdjust = true;
}
previousWidth = currentWidth;
})
// every half second
$(function() {
setInterval('maybeAdjust()', 500);
});
// check the doAdjust flag
function maybeAdjust() {
if (doAdjust) {
adjustBoxHeights();
doAdjust = false;
}
}
// loop through the DIVs and find the height of the tallest one
// then loop again and set them all to that height
function adjustBoxHeights() {
var maxHeight = 0;
$('div#boxes div').each(function(){
$(this).height('auto');
if (maxHeight < $(this).height()) {maxHeight = $(this).height()}
});
$('div#boxes div').each(function(){
$(this).height(maxHeight);
});
}
Otros consejos
Para los otros que, como yo, vinieron aquí buscando una solución en Google: la primera parte de la respuesta aceptada solo funciona cuando el primer div es el más alto. Le hice algunos cambios y ahora parece funcionar en todos los casos.
var highest = 0;
function sortNumber(a,b) {
return a - b;
}
function maxHeight() {
var heights = new Array();
$('#wrapper2>div').each(function(){
$(this).css('height', 'auto');
heights.push($(this).height());
heights = heights.sort(sortNumber).reverse();
});
highest = heights[0];
$('#wrapper2>div').each(function(){
$(this).css('height', highest);
});
}
$(document).ready(function() {
maxHeight();
})
$(window).resize(maxHeight);
Eche un vistazo a este jQuery Plugin que le permite controlar un Propiedad CSS como la altura.
Si desea que funcione al cambiar el tamaño, etc. ... Hágalo así:
function sortNumber(a,b) {
return a - b;
}
var highest = 0;
function maxHeight() {
var heights = new Array();
$('.equalheight div').css('height', 'auto');
$('.equalheight div').each(function(){
heights.push($(this).height());
});
heights = heights.sort(sortNumber).reverse();
highest = heights[0];
$('.equalheight div').css('height', highest);
}
$(document).ready(maxHeight);
$(window).resize(maxHeight);
Encontré esta solución un poco más ordenada para mi situación. Funciona independientemente de qué div es el más alto. Basado en este viejo Chris Coyier publique en CSS Tricks .
function maxHeight() {
var maxHeight = 0;
$(".container > .post-box").each(function(){
if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
});
$(".container > .post-box").height(maxHeight);
}
$(document).ready(function() {
maxHeight();
}
$(window).bind('resize', function () {
$(".container > .post-box").css('height', 'auto');
maxHeight();
}).trigger('resize');
Sin embargo, necesitaba configurar la altura para cambiar automáticamente el tamaño antes de ejecutar la función nuevamente. No necesitaba configurarlo en la función original porque estaba configurado en el CSS.