簡體   English   中英

jQuery比較同一類中的每三個div

[英]Jquery compare every three div in the same class

我在同一個班級有一個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個div,並將高度僅設置為這三個中的最高者。

感謝大家的答復。 對不起,如果讓您感到困惑。我在下面發布一張圖片,每個人都可以理解。

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

在網頁上,框1、2、3在同一行上,我想比較哪個框具有最高的高度,並將其他兩個設置為相同的高度。 然后box4,5,6在新行上,比較這三個,並將每個設置為最高。 因此,第一行和第二行的高度將不同,但是它們都在同一類中。 在這種情況下,由於該行的最高框,如何將每行設置為不同的高度。

您可以遍歷每個第3個div並查找另外兩個:

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個div和其他2個關注者,並且可以彼此進行比較。

第n個孩子的作品。 但這不是模塊化的。 如果希望組大於三個,則需要添加2個步驟。 這是替代代碼,可讓您更改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>');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM