【问题标题】:Pass sass list to mixin with multiple arguments将 sass 列表传递给带有多个参数的 mixin
【发布时间】:2014-02-20 12:24:54
【问题描述】:

我正在尝试创建一个 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");

我知道这是我与包含一起使用的列表,但我不确定如何分解该列表并将其传递给每个参数,或者这是否是最好的方法。

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

感谢您的帮助!

【问题讨论】:

    标签: css sass


    【解决方案1】:

    你可以试试这样的:

    @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

    【讨论】:

    • 我只是想在这里补充一点,在 Sass v3.3 中您将能够进行更多令人兴奋的字符串操作,因此您将能够完全按照您的方式传递列表在你的例子中做。 DEMO。但是您也可以使用这样的自定义 split-string() 函数来获得更优雅的解决方案:https://gist.github.com/chriseppstein/4599879
    • 完美运行!我以前见过这种循环列表的方法,但只有在 mixin 中有一个参数。这非常有用,我为 3.3 感到兴奋。
    猜你喜欢
    • 2011-11-22
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2016-12-15
    • 2012-12-24
    • 2018-10-06
    • 1970-01-01
    • 2015-05-07
    相关资源
    最近更新 更多