使用Sass循环遍历颜色列表

25

可以有三种颜色的列表:

$color-list: x y z;

然后通过循环遍历这三种颜色并将它们添加到无序列表项上来应用这三种颜色。

我想要:

<li>row 1</li> (gets color x)
<li>row 2</li> (gets color y)
<li>row 3</li> (gets color z)
<li>row 4</li> (gets color x)

等等类似的事情。

我曾尝试使用@each函数(http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#each-directive),但它只在遍历列表第一次后停止应用颜色。我希望颜色能够循环应用,直到列表项全部用完为止。

sass可以实现这个吗?


似乎是使用nth-child的情况。Sass不知道你的标记。你可以使用@each迭代列表项,但使用nth-child更灵活。 - steveax
1个回答

49
如果纯CSS可以实现,使用Sass也是可以的。这将适用于任何数量的颜色: http://codepen.io/cimmanon/pen/yoCDG
$colors: red, orange, yellow, green, blue, purple;

@for $i from 1 through length($colors) {
    li:nth-child(#{length($colors)}n+#{$i}) {
        background: nth($colors, $i)
    }
}

输出:

li:nth-child(6n+1) {
  background: red;
}

li:nth-child(6n+2) {
  background: orange;
}

li:nth-child(6n+3) {
  background: yellow;
}

li:nth-child(6n+4) {
  background: green;
}

li:nth-child(6n+5) {
  background: blue;
}

li:nth-child(6n+6) {
  background: purple;
}

我理解这个方法...但是我想让它不断地循环遍历颜色。所以在你的例子中,第7个li会重新从红色开始,直到所有的li元素都被样式化。 - JoshuaRule
4
它确实这样做吗?演示不是展示了吗?这就是 6n+1 的作用:(6 * n) + 1 = 1、7、13、19、25 等。 - cimmanon
我撤回之前的评论。这个很好用!我现在明白你是怎么让它工作的了。 - JoshuaRule
这个工作非常出色...我需要改变走马灯项的颜色,它完成了任务!不过还有一个问题,如何使它随机?那将是最好的! - BelgianCoder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接