Jquery - How to alternate an :Odd :Even pattern every 4 ?

后端 未结 6 1568
无人及你
无人及你 2021-01-06 03:18

I\'m trying to make a pattern in a layout (see attachment for visualisation) The problem is that using :odd :even doesnt work.

I\'ve tried to make it work by using \

6条回答
  •  孤街浪徒
    2021-01-06 03:59

    var i = 1;
    $('#wrapper > div').each(function()
    {
        var isEvenRow = Math.ceil(i / 4) % 2 == 0; // 4 is number of columns
        var isCellAlternate = i % 2 == isEvenRow ? 0 : 1;
    
        if ( isCellAlternate ) {
            $(this).css("background-color", "#000");
        } else {
            $(this).css("background-color", "#ccc");
        }
        i++;
    });​
    

    or the less readable but shorter version:

    var i = 1;
    $('#wrapper > div').each(function() {
        if (i % 2 == (Math.ceil(i / 4) % 2 == 0) ? 0 : 1) $(this).css("background-color", "#000");
        else $(this).css("background-color", "#ccc");
        i++;
    });​
    

    essentially you change the test for the alternate cell every row.

提交回复
热议问题