作者:rtsnance | 来源:互联网 | 2023-05-18 07:02
This question already has an answer here:
这个问题已经有了答案:
- Creating or referencing variables dynamically in Sass 5 answers
- 在Sass 5答案中动态创建或引用变量
I've got a bunch of elements: (#cp1, #cp2, #cp3, #cp4)
我有一些元素:(#cp1, #cp2, #cp3, #cp4)
that I want to add a background colour to using SCSS.
我想为使用SCSS添加一个背景颜色。
My code is:
我的代码是:
$colour1: rgb(255,255,255); // white
$colour2: rgb(255,0,0); // red
$colour3: rgb(135,206,250); // sky blue
$colour4: rgb(255,255,0); // yellow
@for $i from 1 through 4 {
#cp#{i} {
background-color: rgba($(colour#{i}), 0.6);
&:hover {
background-color: rgba($(colour#{i}), 1);
cursor: pointer;
}
}
}
3 个解决方案
28
As @hopper has said the main problem is that you haven't prefixed interpolated variables with a dollar sign so his answer should be marked as the correct, but I want to add a tip.
正如@hopper所说的,主要的问题是你没有在插入变量前加上一个美元符号,所以他的答案应该被标记为正确的,但是我想补充一点。
Use @each
rule instead of @for
loop for this specific case. The reasons:
对于这个特定的情况,使用@each规则而不是@for循环。的原因:
- You don't need to know the length of the list
- 你不需要知道列表的长度
- You don't need to use
length()
function to calculate the length of the list
- 不需要使用length()函数来计算列表的长度
- You don't need to use nth() function
- 不需要使用nth()函数
@each
rule is more semantic than @for
directive
- @每个规则都比@for指令更具有语义性。
The code:
代码:
$colours: rgb(255,255,255), // white
rgb(255,0,0), // red
rgb(135,206,250), // sky blue
rgb(255,255,0); // yellow
@each $colour in $colours {
#cp#{$colour} {
background-color: rgba($colour, 0.6);
&:hover {
background-color: rgba($colour, 1);
cursor: pointer;
}
}
}
Or if you prefer you can include each $colour in the @each directive instead of declare $colors variable:
或者,如果您愿意,可以在@each指令中包含每个$color,而不是声明$colors变量:
$colour1: rgb(255,255,255); // white
$colour2: rgb(255,0,0); // red
$colour3: rgb(135,206,250); // sky blue
$colour4: rgb(255,255,0); // yellow
@each $colour in $colour1, $colour2, $colour3, $colour4 {
#cp#{$colour} {
background-color: rgba($colour, 0.6);
&:hover {
background-color: rgba($colour, 1);
cursor: pointer;
}
}
}
Sass Reference for @each
directive
@每个指令的Sass引用。