Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

css - Accessing an array key in SASS

I have a list in SASS, and I'm trying to access on of the items by using bracket notation:

$collection[1];

but that gives me an error.

Is there any other way to do this?


Why do I want to do this?

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... */

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:

Syntax error: Invalid CSS after "...color-collection": expected ";", was "[ $i ];"


How can I accomplish this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$color-collection: ('red', 'orange', 'green', 'blue');

@for $i from 0 to length($color-collection) {
    .color-#{$i} {
        color: unquote(nth($color-collection, $i+1));
    }
}

Use nth(), also unquote() if you want to pass quoted strings.

Though, I personally wouldn't:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...