1

我正在创建一个 wordpress 主题,并且正在尝试创建一个导航栏,其中每个 li 都有不同的背景颜色(例如红色然后绿色然后蓝色)。然后在使用前三种颜色后,它会再次重复它们。

例如:

<div id="top-nav">
    <ul>
        <a href="#"><li>Hampstead</li></a> background red
        <a href="#"><li>Topsail Beach</li></a> background blue
        <a href="#"><li>North Topsail Beach</li></a> background green
        <a href="#"><li>Surf City</li></a> background red
        <a href="#"><li>Holly Ridge</li></a> background blue
        <a href="#"><li>Sneads Ferry</li></a> background green
    </ul>
</div>

我想将需要 javascript 来识别 li 子编号。

有没有人对我如何做到这一点有任何见解?

感谢您的时间。

4

1 回答 1

4

使用css nth-child 选择器,无需 Javascript 即可轻松实现。尝试类似的东西

li:nth-child(3n)
{
  background:red;
}
li:nth-child(3n-1) 
{
  background:blue;
}
li:nth-child(3n-2) 
{
  background:green;
}

如果你更愿意用 jQuery 来做这件事,它几乎是一样的,因为jQuery 有一个它自己的 nth-child 选择器。然后它会像

$("li:nth-child(3n)").css('background-color', 'red');
$("li:nth-child(3n-1)").css('background-color', 'blue');
$("li:nth-child(3n-2)").css('background-color', 'green');
于 2013-01-24T18:53:33.143 回答