Come posso mantenere più DIV della stessa altezza usando jQuery?
Domanda
Ho alcuni tag DIV con diverse quantità di contenuto testuale.
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>
Sono in un layout due per due e la loro larghezza è fluida:
CSS:
div#boxes {
width: 100%;
}
div#boxes div {
width: 49.9%;
float: left;
}
Li voglio tutti della stessa altezza.
Quindi, li cerco e trovo l'altezza di quella più alta. Quindi giro di nuovo e li metto tutti su quell'altezza.
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);
});
});
Funziona bene se l'altezza del div non deve cambiare di nuovo.
Ma fallisce se ridimensiono la finestra del browser:
-
Se I (a) allarga il browser, allora (b) my I DIV si allargano, quindi (c) il loro testo il contenuto si avvolge meno volte, quindi (d) i miei DIV sono troppo alti.
-
Se I (b) rende il browser più stretto, poi (b) i miei DIV si restringono, quindi (c) il loro contenuto di testo si avvolge di più, e quindi (d) i miei DIV sono troppo corti.
Come posso sia (1) dimensionare automaticamente i DIV all'altezza del loro contenuto come al solito, ma anche (2) mantenere quei DIV multipli alla stessa altezza?
Soluzione
Aggiorna ... riscrivendo completamente questa risposta dopo aver sperimentato e trovato un altro modo apparentemente fattibile per farlo:
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 che ho notato è che IE ha davvero problemi di arrotondamento con div galleggiati larghi del 50% ... il rendering sarebbe molto meglio se li cambiassi al 49%.
Questo jQuery funziona ...
// 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);
});
}
Altri suggerimenti
Per gli altri che, come me, sono venuti qui cercando una soluzione su Google: la prima parte della risposta accettata funziona solo quando il primo div è il più alto. Ho apportato alcune modifiche e ora sembra funzionare in tutti i casi.
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);
Dai un'occhiata a questo Plugin jQuery che ti consente di monitorare un Proprietà CSS come l'altezza.
Se vuoi che funzioni durante il ridimensionamento, ecc ... Fallo in questo modo:
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);
Ho trovato questa soluzione un po 'più ordinata per la mia situazione. Funziona indipendentemente da quale div è il più alto. Basato su questo vecchio Chris Coyier post in 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');
Tuttavia, ho dovuto impostare l'altezza su ridimensionamento automatico prima di eseguire nuovamente la funzione. Non avevo bisogno di impostarlo nella funzione originale perché era impostato nel CSS.