简体   繁体   English

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.当存在嵌套列表时,项目会保持交替,但子项会缩进,而父项的背景颜色不会向下流到其嵌套的子项。嵌套列表示例

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.但如果这是不可能的,3 个深度的上限(如图所示)就足够了。 If it is easier to do by using divs instead of li and ul, that is also possible for me.如果使用 div 而不是 li 和 ul 更容易做到,那对我来说也是可能的。 I prefer pure HTML/CSS.我更喜欢纯 HTML/CSS。

Because all my experiments did no good I can only supply a JSFiddle with the nested lists.因为我所有的实验都没有效果,所以我只能提供带有嵌套列表的 JSFiddle。

https://jsfiddle.net/qmdwpzt8/1/ 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>

Here is one potential solution: https://jsfiddle.net/qmdwpzt8/3/这是一种潜在的解决方案: https : //jsfiddle.net/qmdwpzt8/3/

Not sure if all your requirements will be met by it, but I updated your list with div 's:不确定它是否会满足您的所有要求,但我用div更新了您的列表:

<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>

And then add background colors with jQuery:然后使用 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");
        }            
    });
});

This does depend on jQuery/Javascript.这确实取决于 jQuery/Javascript。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM