CSS嵌套列出项目和备用背景 [英] CSS Nested lists items and alternate background
问题描述
我正在寻找一种方式让列表项具有交替的背景颜色。当存在嵌套列表时,项目保持交替,但是子项缩进,而没有父流的背景颜色到其嵌套的子项。
I am searching for a way to have list items have alternating background colors. When there is a nested list the items keep alternating but the child is indented without having the background color of the parent flow down to its nested children.
无法应用类。项目的数量也是可变的。优选地,它应该工作于无限量的嵌套列表。但如果不可能,3个深度(如图所示)的帽子就足够了。如果使用div而不是li和ul更容易做到,这对我也是可能的。我更喜欢纯HTML / CSS。
It is not possible to apply classes. Also the amount of items is variable. Preferably it should work for an infinite amount of nested lists. But if that is not possible a cap on 3 depths (as in picture) should be enough. If it is easier to do by using divs instead of li and ul, that is also possible for me. I prefer pure HTML/CSS.
因为我的所有实验没有好处,我只能提供一个JSFiddle的嵌套列表。
Because all my experiments did no good I can only supply a JSFiddle with the nested lists.
https://jsfiddle.net/qmdwpzt8/1/
<ul>
<li>Item 1
<ul>
<li>Item 1-1</li>
<li>Item 1-2
<ul>
<li>Item 1-2-1</li>
<li>Item 1-2-2</li>
</ul>
</li>
<li>Item 1-3</li>
</ul>
</li>
<li>Item 2
<ul>
<li>Item 2-1
<ul>
<li>Item 2-1-1</li>
</ul>
</li>
</ul>
</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
推荐答案
这里有一个可能的解决方案: https://jsfiddle.net/qmdwpzt8/3/
Here is one potential solution: https://jsfiddle.net/qmdwpzt8/3/
不确定是否满足您的所有要求,但我使用 div
更新您的列表:
Not sure if all your requirements will be met by it, but I updated your list with div
's:
<ul>
<li><div>Item 1</div>
<ul>
<li><div>Item 1-1</div></li>
<li><div>Item 1-2</div>
<ul>
<li><div>Item 1-2-1</div></li>
<li><div>Item 1-2-2</div></li>
</ul>
</li>
<li><div>Item 1-3</div></li>
</ul>
</li>
<li><div>Item 2</div>
<ul>
<li><div>Item 2-1</div>
<ul>
<li><div>Item 2-1-1</div></li>
</ul>
</li>
</ul>
</li>
<li><div>Item 3</div></li>
<li><div>Item 4</div></li>
</ul>
然后使用jQuery添加背景颜色:
And then add background colors with jQuery:
$( document ).ready(function() {
var b = true;
$( "div" ).each(function( index ) {
b = !b;
if (b) {
$(this).css("background-color", "#ff0000");
} else {
$(this).css("background-color", "#00ff00");
}
});
});
这取决于jQuery / Javascript。
This does depend on jQuery/Javascript.
这篇关于CSS嵌套列出项目和备用背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!