gpt4 book ai didi

javascript - li 背景颜色重复/图案

转载 作者:行者123 更新时间:2023-11-30 10:35:04 25 4
gpt4 key购买 nike

我正在创建一个 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 child 号码。

有人知道我该怎么做吗?

感谢您的宝贵时间。

最佳答案

使用 css nth-child selector ,您无需 Javascript 即可轻松实现此目的。尝试类似的东西

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

如果您更愿意使用 jQuery 执行此操作,它几乎与 jQuery has an nth-child selector 相同它自己的。然后它会像

$("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');

关于javascript - li 背景颜色重复/图案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14508372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com