2013-10-17 24 views
4

我想設置配對的div高度相同。設置兄弟姐妹DIV等高(最高)

<div class="item "> 
Some text 
</div> 
<div class="item right"> 
Some text 
</div> 
<div class="item "> 
Some text<br/>Some text<br/>Some text<br/>Some text<br/>Some text 
</div> 
<div class="item right"> 
Some text<br/>Some text<br/>Some text<br/>Some text 
</div> 
<div class="item "> 
Some text 
</div> 
<div class="item right"> 
Some text<br/>Some text<br/>Some text 
</div> 

CSS

.item{width: 45%;float: left;position: relative;border: 1px solid #000;clear:left;} 
.item.right{float:right;clear:right;} 

的jQuery我使用

$('.item.right').prev().each(function() { 
    leftheight = $(this).height(); 
    rightheight = $(this).next().height();  
    if(leftheight > rightheight){ 
     $(this).next().height(leftheight); 
    }else{ 
     $(this).height(rightheight); 
    }    
}); 

這似乎並不工作,我想不通爲什麼。

我有兩個列布局,其中divs有一個針腳線邊框,所以當它們不是相同的高度時它是非常明顯的。 '正確的班級'將項目向右移動。 我只想要這兩對高度相同,因爲它們會形成一排。我不想使用表格(CSS或其他),因爲佈局對於移動設備是動態的(它們形成單個列)。

回答

5

您可以使用map()得到div左/右元件的高度在一個數組,然後Math.max陣列上獲得最高的,併爲他們兩個使用該值。試試這個:

$('.item.right').each(function() { 
    var $divs = $(this).add($(this).prev('.item')); 
    var tallestHeight = $divs.map(function(i, el) { 
     return $(el).height(); 
    }).get(); 
    $divs.height(Math.max.apply(this, tallestHeight)); 
}); 

Example fiddle

+0

這比我的答案要好。 – Jai

1

您必須首先檢索最大高度,然後將所有高度設置爲該高度。

像這樣:

var max_height = 0; 
$('.item.right').prev().each(function() { 
    if($(this).height() > max_height) { 
    max_height = $(this).height(); 
    } 
}); 
$('.item.right').prev().each(function() { 
    $(this).height(max_height); 
} 

編輯

因此錯誤是next()因爲你已經在正確的項目,你比較與next()一個...使用prev(),而不是!

$('.item.right').prev().each(function() { 
rightheight = $(this).height(); 
leftheight = $(this).prev().height();  
if(rightheight > leftheight){ 
    $(this).prev().height(rightheight); 
}else{ 
    $(this).height(leftheight); 
}    
}); 
+0

我不想將所有的高度相同..只是對每一行。 – Elijha

+0

你可以通過投票來告訴我我錯過了什麼 - 但是Rory的答案似乎更加高效和靈活。 – Elijha

+0

謝謝你,當然這是最漂亮的,但我不知道有關性能... – JoDev

2

你可以用這個(.map() and Math.max.apply())嘗試:

你必須得到高度數組中,並查找數組中的最大值,然後Math.max.apply()將從陣列應用的最大價值。

$(document).ready(function() { 
    var heightArray = $(".item").map(function() { 
     return $(this).height(); 
    }).get(); 
    var maxHeight = Math.max.apply(Math, heightArray); 
    $(".item").height(maxHeight); 
}); 

Tryout the fiddle

2

工作演示http://jsfiddle.net/nTFtn/http://jsfiddle.net/6tU2m/

這是你在尋找什麼!

希望這有助於:)

代碼

$('.item.right').prev('div').each(function() { 

    leftheight = $(this).height(); 
    alert(leftheight); 
    rightheight = $(this).next().height(); 
    if (leftheight > rightheight) { 

     $(this).next().height(leftheight); 
    } else { 
     $(this).height(rightheight); 
    } 
}); 
+1

是prev('div')的唯一改變你對我的代碼所做的補充..是所有這些遺失? – Elijha

+0

@Elijha':''確實是布魯夫,看起來它:)')'休息你有解決方案! –