首页 文章

Sass Mixin参数 - 阻止Sass转换分数(例如1/3转换为0.33333)?

提问于
浏览
1

情况

我有这样的Mixin:

@mixin column($fraction: null) {
    // ...do stuff with $fraction
}

它可以像这样使用:

@include column('1/3');

请注意:

  • 传递一个字符串

  • 我需要分母(3)做一些n-child魔法 .

这工作(使用str-index str-slice) .

问题

现在我想让引号可选 .
意思是,这也需要工作:

@include column(1/3); // no quotes

Sass将此视为一个数字 . 没关系 .
但它总是 a division before I can do anything with the variable .

示例

包括:

@include column(1/3);

混入:

@mixin column($fraction: null) {
    $myVar: $fraction // $fraction equals '0.3333333' at this point already
}

有没有办法阻止Sass这样做?或者另一种获得分母的方法?

谢谢!


附加说明

About using a Comma instead of Slash

正如@Johannes Reuter所提出的,我可以使用逗号而不是斜杠:

@include column(1,3);

不幸的是,包含失去了一些意义 .
有一个"1/3"它's clear that the column will be one third in width. I'喜欢保持这一点 .

它特别容易混淆更多参数:

@include column(1, 3, 3, stacking);

VS

@include column(1/3, 3, stacking);

但是非常感谢这个答案 .

2 回答

  • 1

    您可以将分子和分母作为两个单独的参数传递:

    包括:

    @include column(1,3);
    

    混入:

    @mixin column($numerator: null, $denominator: null) {
     //...
    }
    

    这比字符串操作更清晰 .

  • 1

    是一个肮脏的技巧,但如果您使用参数列表,您获得没有除法的值,那么您必须转换为字符串以使用 str-slice 提取第二个值:

    SASS

    @mixin column($fraction...) {
      $fraction: $fraction + "";
      $n:str-slice($fraction, 3);
      &:nth-child(#{$n}){
        display:block;
      }
    }
    
    .class{
      @include column(1/3);
    }
    

    OUTPUT

    .class:nth-child(3) {
      display: block;
    }
    

    PS: 问题是如果要使用更多参数 . 我不知道如何解决它 .


    UPDATE 28/09/2016

    我找到了一种方法来处理两个mixins,一个带有参数列表和css属性,另一个带有 variable arguments ,其中我在除法运算符后提取数字 .

    变量参数阻止进行除法,但所有参数都在一起,如果我提取第一个参数,则除法再次执行 . 使用两个不同的mixin我可以使用变量参数,同时维护单独的参数:

    SASS

    @mixin column2($col, $gutter) { 
      width: $col * 100%;
      padding: $gutter;
    }
    
    @mixin column($args...) { 
      $args-str: inspect($args);
      $separator: str-index($args-str, ",");
      $separator2: str-index($args-str, "/");
      $fraction: str-slice($args-str, 1, $separator - 1);
      $cols: unquote(str-slice($fraction, $separator2 + 1));
      &:nth-child(#{$cols}){
        @include column2($args...);
      }
    }
    
    .class {
      @include column(1/3, 3px);
    }
    

    OUTPUT

    .class:nth-child(3) {
      width: 33.33333%;
      padding: 3px;
    }
    

相关问题