我想出了以下自定义jQuery代码来计算div如何排列成行,然后循环遍历每行并为行中每个div的内容计算出正确的最大高度,然后设置该行中所有div的高度。
$(window).resize(function() {
var $blocks = $('.block'),
firstBlockTop = $blocks.first().offset().top,
lastOffsetTop = firstBlockTop;
var rows = [],
currentRow = 0,
i, rowCount, j, colCount, height;
$blocks.each(function(index, element) {
var $div = $(element),
thisOffsetTop = $div.offset().top;
if (thisOffsetTop !== lastOffsetTop) {
currentRow++;
}
rows[currentRow] = (rows[currentRow] || []);
rows[currentRow].push($div);
lastOffsetTop = thisOffsetTop;
});
console.log(rows);
function maxHeight(array) {
var maxHeight = -1,
innerHeight;
for (var i = 0, len = array.length; i < len; i++) {
// calculate the actual total height for the inner items
innerHeight = 0;
array[i].children().each(function() {
innerHeight += $(this).outerHeight(true);
});
maxHeight = Math.max(innerHeight, maxHeight);
}
return maxHeight;
}
// now loop through each row and set the height of each div to the max height for the row
for (i = 0, rowCount = rows.length; i < rowCount; i++) {
height = maxHeight(rows[i]);
console.log('Row ' + i + ', maxHeight = ' + height);
for (j = 0, colCount = rows[i].length; j < colCount; j++) {
rows[i][j].height(height);
}
}
});
您可能会对此代码做出轻微的性能改进,但希望它能为您提供良好的基准。自带权在我脑海
这不会让所有div是同一高度或跨页对齐。 – 2012-03-30 04:35:08