对于SCSS中的循环与变量的组合

tob*_*byn 32 html css sass

我有很多元素:(#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)

  • 获取列表长度可能更好,而不是硬编码:`@for $ i从1到长度($ colors){...` (15认同)

Ale*_*ero 36

正如@hopper所说,主要的问题是你没有用美元符号作为插值变量的前缀,所以他的答案应该被标记为正确,但我想添加一个提示.

对于此特定情况,请使用@each规则而不是@for循环.原因:

  • 您不需要知道列表的长度
  • 您不需要使用length()函数来计算列表的长度
  • 您不需要使用nth()函数
  • @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)

@each指令的Sass参考


hop*_*per 18

SASS变量仍然需要在插值中加上美元符号作为前缀,所以你拥有的每一个地方都#{i}应该是#{$i}.您可以在SASS参考中查看插值的其他示例.