Como faço para manter vários DIVs a mesma altura usando jQuery?
Pergunta
Eu tenho algumas tags DIV com diferentes quantidades de conteúdo 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>
Eles estão em um layout de dois-por-dois e sua largura é fluido:
CSS:
div#boxes {
width: 100%;
}
div#boxes div {
width: 49.9%;
float: left;
}
Eu quero-os todos a mesma altura.
Então, eu loop através deles e encontrar a altura de cada um mais alto. Então ciclo I novamente e defini-los todos para essa 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);
});
});
Isso funciona bem se a altura da div não precisa mudar novamente.
Mas, ele não consegue se eu redimensionar a janela do navegador:
-
Se I (a) tornar o navegador mais ampla, então (b) o meu DIVs obter mais amplo, em seguida, (c) o seu texto conteúdo envolve menos vezes, e depois (d) meus DIVs são muito altas.
-
Se I (b) tornar o navegador mais estreita, então (b) os meus DIVs obter mais estreito, em seguida, (c) seu conteúdo texto quebra mais, e em seguida, (d) os meus DIVs são muito curtos.
Como faço para ambos (1) DIVs automaticamente tamanho para a altura do seu conteúdo como normal, mas também (2) manter os vários DIVs a mesma altura?
Solução
Atualizar ... reescrever completamente esta resposta depois de experimentar e encontrar uma outra maneira, aparentemente viável fazer isso:
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);
Uma coisa que notei é que o IE realmente tem arredondamento problemas com 50% divs ampla flutuavam ... a prestação foi muito melhor se eu mudei aqueles para 49%.
Esta 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);
});
}
Outras dicas
Para os outros que, como eu, vieram para cá por pesquisar no Google por uma solução: A parte punho da resposta aceita só funciona quando o primeiro div é o mais alto. Eu fiz algumas mudanças para ele e agora ele parece funcionar em todos os 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);
Confira este jQuery Plugin que lhe permite monitorar um propriedade CSS, tais como a altura.
Se você quer que ele funcione quando redimensionamento etc ... Faça-o assim:
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);
Eu encontrei esta solução a ser um pouco mais arrumado para a minha situação. Ele funciona independentemente de qual div é o mais alto. Baseado lo neste velho Chris Coyier posto na Truques CSS .
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');
No entanto, eu tinha necessidade de definir a altura de auto em redimensionar antes de executar a função novamente. Eu não precisará configurá-lo na função original porque foi definido no css.