根据 LI 位置添加类

Adding class as per LI postion

本文关键字:添加 位置 LI 根据      更新时间:2023-09-26

我有下面的标记,

<ul>
<li>1</li> //light BG
<li>2</li>
<li>3</li>
<li>4</li> //light BG
<li>5</li>
<li>6</li>
......
</ul>

我想根据li的位置添加类darklight

  • light首先li
  • 2,第3应dark
  • 4、第5应light
  • 同样的模式....
$('ul li:nth-child(3n-2)').addClass('light');
$('ul li::not(:nth-child(3n-2))').addClass('dark');

演示

玩模运算符,很有趣!

$( 'li' ).each( function() {
    // Cache some variables
    var el = $( this ),
        index = el.index();
    if ( index % 3 === 0 || index % 3 === 1 ) {
        el.addClass( 'light' );
    }
    else {
        el.addClass( 'dark' );
    }
} );

PS:感谢Zeta帮助我进行模运算/o/

这是你所追求的模式吗:

http://jsfiddle.net/rCkQV/

如果其他的都是黑暗的,他们可以继承所有LI的类集,并且光会覆盖这一点。

$("ul li:nth-child(4n),ul li:nth-child(4n+1)").addClass("light");