2

我试图制作一个获取参数(可以是变量列表)的mixin,然后在列表的最后一项之后不输出逗号。这是迄今为止的mixin:

   @mixin i-class($name...,$pua) {
      @if type-of($name) == "list" {
          @for $className from 1 through length($name) {
              .#{$classIcon}.#{$className}:before,
          } 
              { content: "\e#{$pua}";}
          }
      }
      @else {
          .#{$classPrefix}.#{$name}:before { 
            content: "\e#{$pua}";
          }
      }
    }

如果像这样传递一个参数,这将是所需的输出:

@include i-class(someIcon,"000");

.icon.someIcon:before {
    content: "\e000";
}

如果传递了多个参数(一个列表),那么输出将是这样的:

@include i-class(someIcon,someIcon2,someIcon3,"001");

.icon.someIcon:before, .icon.someIcon2:before, .icon.someIcon3:before {
    content: "\e001";
}

我只是不知道用什么来检查它是否是列表中的最后一项,然后省略逗号。帮助将不胜感激:)

4

2 回答 2

1

包罗万象的参数必须是 mixin 中的最后一个参数。利用列表创建选择器比自己手动插入逗号更简单:

@mixin i-class($pua, $name...) {
    $selector: ();

    @each $className in $name {
        $selector: append($selector, unquote('.#{$classIcon}.#{$className}:before'), comma);
    }

    #{$selector} {
        content: "\e#{$pua}";
    }
}
于 2013-08-04T11:35:42.863 回答
0

@cimmonon 的回答很好,但如果你想避免重复,你可以尝试使用占位符。像那样:

$classPrefix: ".icon";
$i-class-stack: ();

@mixin i-class($pua, $names...) {
  // A stack is used to create a placeholder by `$pua`.
  @if not index($i-class-stack, $pua) {
    $i-class-stack: append($i-class-stack, $pua);
    %i-class-#{$pua} {
      content: "\e#{$pua}";
    }
  }
  @each $name in $names {
    #{$classPrefix}.#{$name}:before {
      @extend %i-class-#{$pua};
    }
  }
}

// First call to the mixin to generate a rule with `content: "\e001"`.
@include i-class("001", someIcon, someIcon2);

// Do stuff
.foobar {
  background-color: blue;
}

// Another call to the i-class mixin, but with a new value.
@include i-class("025", someIcon, someIcon2);

// Now, we add some new selectors to the first CSS rule
// (with `content: "\e001"`).
@include i-class("001", someIcon3, someIcon4);

查看输出:

.icon.someIcon:before, .icon.someIcon2:before, .icon.someIcon3:before, .icon.someIcon4:before {
  content: "\e001";
}

.foobar {
  background-color: blue;
}

.icon.someIcon:before, .icon.someIcon2:before {
  content: "\e025";
}
于 2013-08-04T13:23:47.053 回答