将sass列表传递给具有多个参数的mixin

时间:2014-01-28 22:47:41

标签: css sass

我正在尝试创建一个sass mixin,它会将列表中未定数量的项目作为mixin中的参数。

最终目标是使用一个mixin,可用于为进度条设置不同值的颜色样式(即当条形值较低时为红色)。以下是我为mixin提出的建议:

@mixin progress-value($value..., $color...) {

    progress[value="#{$value}"] { 
        color: #{$color}; 

        &::-webkit-progress-value { background-color:  #{$color}; }
        &::-moz-progress-bar { background-color: #{$color}; }
    }   
}

// Calling the mixin
@include progress-value("0.25, #de2b23", "0.5, #FF8330", "0.75, #8A9F4A", "1, #14BB64");

我知道这是一个我正在使用include的列表,但是我不知道如何打破该列表并将其传递给每个参数,或者这是否是最好的方法。

我可以创建一个更简单的mixin版本,并为每个被设置样式的值调用它,但这看起来不是很干。

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

您可以尝试这样的事情:

@mixin make_progress($val,$col){
  progress[value="#{$val}"] {
    color: #{$col};
    &::-webkit-progress-value { background-color:  #{$col}; }
    &::-moz-progress-bar { background-color: #{$col}; }
  }  
}

@mixin progress-value($value-color...) {
    @each $progress in $value-color {
      @include make_progress(nth($progress,1),nth($progress,2));
    }
}

// Calling the mixin
@include progress-value(0.25 #de2b23);
// and with a multideimensional list
@include progress-value(0.5 #FF8330, 0.75 #8A9F4A, 1 #14BB64);

如果您将参数作为逗号分隔的空格分隔对的列表 - 值/颜色传递,就像我在上面的示例中所做的那样,或者在通过其他方式明确指出您的参数列表是多维 - 比如在括号中包含每个传递的对:

// with a single parameter
@include progress-value((0.25, #de2b23));
// or with multiple parameters
@include progress-value((0.5, #FF8330), (0.75, #8A9F4A), (1, #14BB64));

我还创建了一个单独的mixin make_progress,以获得更好的概述,如果你想在循环外的其他实例中调用它,但你可以轻松地将它留在循环中。

DEMO

相关问题