2015-02-11 19 views
1

我有一個在同一類中的div列表。我想比較他們每三個,並將高度設置爲最高。例如:jquery比較同一類中的每三個div

<ul> 
<li class="items">box1</li> 
<li class="items">box2</li> 
<li class="items">box3</li> 

<li class="items">box4</li> 
<li class="items">box5</li> 
<li class="items">box6</li> 

<li class="items">box7</li> 
<li class="items">box8</li> 
<li class="items">...</li> 
</ul> 

什麼我發現了迄今能找到的最高的高度所有列表中,並使用jquery每個列表設置爲高。

function equalHeight(group) { 
    tallest = 0; 
    group.each(function() { 
     thisHeight = $(this).height(); 
     if (thisHeight > tallest) { 
      tallest = thisHeight; 
     } 
    }); 
    group.height(tallest); 
} 

     window.onload=(function() { 
     equalHeight($('.items')); 
}); 

有沒有一種方法可以比較列表中的每3格,並將高度設置爲僅在這三者中最高。

感謝大家的回覆。對不起,如果我讓你感到困惑。我發表下面的圖片更好地讓大家理解。

http://i62.tinypic.com/2e0vayf.jpg

在網頁中,box1,2,3在同一行,我想比較這盒具有最高的高度並設置其他兩個是相同的高度。然後box4,5,6在一個新的線上,比較這三個並將每一個設置爲最高。所以第一行和第二行會有不同的高度,但他們都在同一個班級。如何將每條線設置爲不同的高度,因爲這種情況下該線的最高方框。

+1

你爲什麼要使用腳本對於這一點,聽起來像一個CSS問題?你最終的目標是什麼? – Nit 2015-02-11 20:09:53

+0

什麼決定了最高的div的高度? – 2015-02-11 20:11:04

回答

1

您可以通過每個第3格迭代,並找到未來的2人:

jQuery(document).ready(function($){ 
    $("ul li:nth-child(3n+1)").each(function(){ 
     var first = $(this); 
     var second = first.next(); 
     var third = second.next(); 
    }); 
}); 

因此,使用nth-child你每3格等2個追隨者,你可以比較互相這種方式。

0

n-child作品。但它不是模塊化的。如果您希望組數大於三,則需要添加兩個步驟。這裏有一個替代代碼,可以讓您更改1號碼並更改分組大小。

JSFiddle

/*Sets up our counting variables*/ 
var count = 0; 
var height = 0; 
var groups = 0; 
var tallest = 0; 
var number_of_items_in_group = 3; 
/*grabs the index length of list items*/ 
var indexL = $('li').length; 
/*Every li item is looped through*/ 
$('li').each(function (index, element) { 
    count++; 
    /*if the count % number_of_items_in_group returns anthing but a 0 it adds the height 
    if you change 3 to 4 it will count elements in groups of 4 rather than three 
    */ 
    if (count % number_of_items_in_group) { 
     height += $(this).height(); 
    } else { 
     /*adds the height, adds to group, sets the tallest, and appends to results*/ 
     groups++; 
     height += $(this).height(); 
     count = 0; 
     if (height > tallest) { 
      tallest = height 
     } 
     $('#results').append('<p>' + height + ' Pixels: ' + groups + '</p>'); 
     height = 0; 
    } 

}); 
/*if the last group is less than number of items in group it will still 
add the last group even though it has lower ammount of items in the group*/ 
if (indexL % number_of_items_in_group) { 
    groups++; 
    $('#results').append('<p>' + height + ' Pixels: ' + groups + '</p>'); 
    height = 0; 
} 
/*shows tallest*/ 
$('#results').append('<p>' + tallest + ' Pixels: Tallest</p>');