基本上,我有一个插件可以生成由一个 <ul>
组成的 HTML 菜单。标签和几个 <li>
标签。我想为每个菜单项应用不同的背景颜色,但我无法将这些 CSS 类添加到每个列表项,因为它们是以编程方式生成的,因此无法直接访问。有没有办法将不同的类应用于同一标签的多个子元素?在我的例子中,没有访问插件文件。
最佳答案
是的,这是可能的。
您可以使用 nth-of-type(n)目标不同的选择器 <li>
元素而不向生成的代码添加类。
body {font-size: 22px}
ul li:nth-of-type(1){background:red}
ul li:nth-of-type(2){background:blue}
ul li:nth-of-type(3){background:green}
ul li:nth-of-type(4){background:yellow}
ul li:nth-of-type(5){background:orange}
ul li:nth-of-type(6){background:purple}
ul li:nth-of-type(7){background:cyan}
ul li:nth-of-type(8){background:brown}
ul li:nth-of-type(9){background:pink}
<ul>
<li>Apple</li>
<li>Orange</li>
<li>Watermelon</li>
<li>Pear</li>
<li>Milk</li>
<li>Cheese</li>
<li>Bread</li>
<li>Jam</li>
<li>Sugar</li>
</ul>
您还可以使用页面上的其他元素来确保更改仅应用于您想要影响的元素。
例子:
body {
font-size: 22px
}
.foo ul li:nth-of-type(1) {
background: red
}
.foo ul li:nth-of-type(2) {
background: blue
}
.foo ul li:nth-of-type(3) {
background: green
}
.foo ul li:nth-of-type(4) {
background: yellow
}
<div class="bar">
<h1> First List (not modified)</h1>
<ul>
<li>Apple</li>
<li>Orange</li>
<li>Watermelon</li>
<li>Pear</li>
</ul>
</div>
<div class="foo">
<h1> Second List (modified)</h1>
<ul>
<li>Apple</li>
<li>Orange</li>
<li>Watermelon</li>
<li>Pear</li>
</ul>
</div>
<div class="bar">
<h1> Third List (not modified)</h1>
<ul>
<li>Apple</li>
<li>Orange</li>
<li>Watermelon</li>
<li>Pear</li>
</ul>
</div>
关于html - 将 CSS 类应用于同一标签的插件生成元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47355724/