在SASS中访问阵列键 [英] Accessing an array key in SASS
问题描述
我在SASS中有一个列表,我正在尝试使用方括号表示法访问其中的项:
I have a list in SASS, and I'm trying to access on of the items by using bracket notation:
$collection[1];
但这给了我一个错误.
还有其他方法吗?
我为什么要这样做?
我有一个颜色列表,必须根据服务器分配给它们的颜色在不同的元素上进行设置.标记具有编号的类别(color-0
,color-1
等).这是我想要的CSS:
I have a list of colors that have to be set on different elements according to a colors assigned to them by the server. The markup has numbered classes (color-0
, color-1
, etc.). Here's the CSS I'm aiming for:
.color-0 { color: red }
.color-1 { color: orange }
.color-2 { color: green }
.color-3 { color: blue }
/* many more, with more complex colors... */
我认为我可以使用带循环的SASS集合,而不是手工编写所有内容:
Instead of writing it all by hand, I figured I could use a SASS collection with a loop:
$color-collection: ('red', 'orange', 'green', 'blue');
$color-count: length($color-collection);
@for $i from 0 to $color-count {
.color-#{$i} {
color: $color-collection[ $i ];
}
}
但这只会给我以下错误:
but this just gives me the following error:
语法错误:"... color-collection"之后的CSS无效:预期的;"为"[$ i];"
Syntax error: Invalid CSS after "...color-collection": expected ";", was "[ $i ];"
我该怎么做?
推荐答案
$color-collection: ('red', 'orange', 'green', 'blue');
@for $i from 0 to length($color-collection) {
.color-#{$i} {
color: unquote(nth($color-collection, $i+1));
}
}
还要使用 nth()
unquote()
如果要传递带引号的字符串.
Use nth()
, also unquote()
if you want to pass quoted strings.
但是,我个人不会:
$color-collection: (red, rgba(50,50,80, .5), darken(green, 50%), rgba(blue, .5));
@for $i from 0 to length($color-collection) {
.color-#{$i} {
color: nth($color-collection, $i+1);
}
}
因为这样您就可以传递任何颜色的对象.
Because then you can pass any color object.
这篇关于在SASS中访问阵列键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!