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

后端 未结 6 1634
无人及你
无人及你 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 04:18

    Not sure how your markup goes, but you can use the :nth-child(n) selector to achieve a checkerboard effect. I've set up an example for you here. I'm not sure how efficient it will be, although it seems fast enough for a 4x4 grid.

    $("div:nth-child(8n+2),div:nth-child(8n+4),div:nth-child(8n+5),div:nth-child(8n+7)")
        .css({"background-color":"white"});​
    

    This repeats a pattern on the 2nd, 4th, 5th and 7th every 8 divs (8n). If you have a different size grid, you'll have to tweak these selectors (and add to them).

    It's much simpler if you're using a table - example:

    $("tr:odd > td:even, tr:even > td:odd").css({"background-color":"white"});​
    

    If you're willing to use wrapper divs, you can use the rows technique, wrapping every 4 divs in an outer div and using:

    1
    2
    3
    4
    1
    2
    3
    4
    1
    2
    3
    4
    1
    2
    3
    4
    $(".row:odd > div:even, .row:even > div:odd").css({"background-color":"white"});​

提交回复
热议问题