访问迭代器并将其附加到 SASS 中的变量名

问题描述:

我对 sass 很陌生.我定义了 14 个不同的变量 $skill-1、$skill-2 等,它们具有不同的值,并为不同的 ID 调用不同宽度的 mixin.

I'm quite new to sass. I'm defining 14 different variables $skill-1, $skill-2 etc. with different values and calling a mixin to different widths to different IDs.

我收到一个错误

Undefined variable: "$skill-".

这是我的代码示例.

@mixin skill-func($val) {
       & { width : $val; }
    }
    $i: 14;
    @while $i > 0 {
      #skill-#{$i} { 
            @include skill-func ($skill-#{$i})
       }
      $i: $i - 1;
    }

不幸的是你不能动态调用这样的变量(没有变量插值 - 参见字符串示例 此处插入插值).

Unfortunately you can not dynamically call a variable like that (there is no variable interpolation - see examples of string interpolations here).

但是您可以将所有 14 个值保存在一个列表中,然后使用 nth() 函数调用相应的项目.一些类似的东西:

But you could save all your 14 values in a list and then call the respective item using the nth() function. Something along these lines:

$skill: 12px, 23px, 42px, 234px, 440px;

@mixin skill-func($val) {
   & { width : $val; }
}

$i: 5;

@while $i > 0 {
  #skill-#{$i} { 
        @include skill-func (nth($skill, $i))
   }
  $i: $i - 1;
}

演示

或者可以使用 ma​​p (那么你也可以使用不是数字的键,并且可以生成语义上更有意义的 id - 当这更有意义时).

DEMO

Alternatively a map could be used (then you can also use keys that are not numbers and can generate semantically more meaningful ids - when that makes more sense).

$skill: (supernarrow:12px, narrow:23px, normal:42px, wide:234px, superwide:440px);

@mixin skill-func($val) {
   & { width : $val; }
}

@each $key, $i in $skill {
  #skill-#{$key} { 
        @include skill-func ($i);
   }
}