【问题标题】:Use variable value in @each在@each 中使用变量值
【发布时间】:2018-12-13 10:00:24
【问题描述】:

我想在@each: 中使用一个变量值来为不同的状态创建类。 但是SASS不使用值,它放在变量名中。

有这个 SASS 语法:

$success: green;
$warning: yellow;
$danger: red;
$information: steelblue;

@mixin theme ($color) {
  &:checked {
    background: $color;
  }

@each $theme in success, warning, danger, information {
  .checkbox--#{$theme} {    
    @include theme($theme);
  }
}

mixin 不会使用 $warning 值,而是创建

color: warning

我该如何解决?

【问题讨论】:

    标签: css sass scss-mixins


    【解决方案1】:

    SCSS 中没有动态变量名称,但您可以改用 Map

    $success: green;
    $warning: yellow;
    $danger: red;
    $information: steelblue;
    
    @mixin theme ($color) {
        &:checked {
            background: $color;
        }
    }
    
    $themes: (
        success $success,
        warning $warning,
        danger $danger,
        information $information
    );
    
    @each $theme, $color in $themes {
        .checkbox-#{$theme} {
            @include theme($color);
        }
    }
    

    为了完整起见,如果您使用的是不支持它们的真正旧版本的 SCSS,您可以使用嵌套的 Listsnth 函数。

    ...
    
    $themes: (
        (success $success),
        (warning $warning),
        (danger $danger),
        (information $information)
    );
    
    @each $pair in $themes {
        $theme: nth($pair, 1);
        $color: nth($pair, 2);
    
        .checkbox-#{$theme} {
            @include theme($color);
        }
    }
    

    两者都会产生相同的输出:

    .checkbox-success:checked {
        background: green;
    }
    
    .checkbox-warning:checked {
        background: yellow;
    }
    
    .checkbox-danger:checked {
        background: red;
    }
    
    .checkbox-information:checked {
        background: steelblue;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-14
      • 2012-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-14
      • 2014-10-04
      • 2019-07-13
      相关资源
      最近更新 更多