0

我有 3 个.items_rowdiv,每个包含 4 个.item,每个.item包含一个.item_img. 我正在使用以下脚本.item_img在 each.item中找到最高的.items_row,并为最短的添加底部边距,即最高.item_img高度减去每个最短的高度。

$('.items_row').each(function(){
    var tallestimg = -1;
    $(this).children().each(function() {
        $(this).find('.item_img').each(function(i) {
            tallestimg = $(this).height() > tallestimg ? $(this).height() : tallestimg;
            if ($(this).height() < tallestimg) {
                $(this).css({ 'margin-bottom': tallestimg - $(this).height() });
            }
        });
    });
});

该脚本完全按照我的意愿工作,但如果最高的.item_imgdiv 不在第一个.itemdiv 中,那么最短的 div 在它根本没有得到之前margin-bottom。例如,如果最高的.item_imgdiv 位于 的第二个.item.items_row,则.item_img前面的 div 会忽略margin-bottom。有任何想法吗?

4

4 回答 4

1

您的解决方案不起作用,因为您没有为最高之前的图像设置边距底部。如果您的图像从最短到最高排序,则所有图像的 margin-bottom = 0。

您应该首先搜索最高的图像,然后再次遍历图像以应用所需的边距底部。

我认为这应该有效:

$('.items_row').each(function(){
    var tallestimg = -1;
    $(this).children().each(function() {
        $(this).find('.item_img').each(function(i) {
            tallestimg = $(this).height() > tallestimg ? $(this).height() : tallestimg;            
        });
    });

    $(this).children().each(function() {
        $(this).find('.item_img').each(function(i) {
            if ($(this).height() < tallestimg) {
                $(this).css({ 'margin-bottom': tallestimg - $(this).height() });
            }
        });
    });


});
于 2012-12-19T09:01:34.540 回答
0

试试这个:

$('.items_row').each(function() {
    var $rowItems = $('.items', this)

    // get the height of the tallest .item in the row
    var maxHeight = $rowItems.map(function(index, element) {
        return $(element).height();
    }).get();

    // apply the required margin-bottom to each .item
    $rowItems.each(function() {
        $(this).css({ 'margin-bottom': maxHeight - $(this).height() })
    });
});
于 2012-12-19T08:58:21.340 回答
0

首先得到最高的图像:

var max_height = Math.max.apply(
    null,
    $('.item_img').map(function(ix, el){ 
        return $(el).height(); 
    }).get()
)

然后应用边距:

$('.item_img').each(function(){
    $(this).css({'margin-bottom': max_height - $(this).height()});
});
于 2012-12-19T09:03:24.127 回答
0

看到这个:http: //jsfiddle.net/pPTkL/1/

$('.items_row').each(function() {
 var height= -1;
 $(this).find('.item_img').each(function() {
     height = Math.max(height, $(this).height()); 
 });

 $(this).find('.item_img').each(function() {
     $(this).css('margin-bottom',(height - $(this).height()));
 });
});​
于 2012-12-19T09:18:07.817 回答