我有很多元素:(#cp1,#cp2,#cp3,#cp4)
我想为使用SCSS添加背景颜色.
我的代码是:
$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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Xab*_*iel 57
您可以创建一个列表并使用该nth方法获取值,而不是使用插值生成变量名称.要使插值工作,语法应该#{$i}如漏斗所述.
$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
$colors: $colour1, $colour2, $colour3, $colour4;
@for $i from 1 through length($colors) {
#cp#{$i} {
background-color: rgba(nth($colors, $i), 0.6);
&:hover {
background-color: rgba(nth($colors, $i), 1);
cursor: pointer;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*ero 36
正如@hopper所说,主要的问题是你没有用美元符号作为插值变量的前缀,所以他的答案应该被标记为正确,但我想添加一个提示.
对于此特定情况,请使用@each规则而不是@for循环.原因:
length()函数来计算列表的长度@each规则比@for指令更具语义代码:
$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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者如果您愿意,可以在@each指令中包含每种$颜色,而不是声明$ 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)