mixin创建的选择器聚合可能吗?

时间:2013-05-03 18:40:52

标签: sass

我尝试让mixin“记住”它正在生成的选择器,这样我就可以在最后制作一个批量选择器。

为了说明我想要做什么 - 我的mixin看起来像这样:

@mixin fontcustom($name) {
  @if $name == "heart" {
    $glyph: '\2764'; // a special character in my own font -> ❤
  }
  @else if $name == "foo" { ... }
  @else if $name == "bar" { ... }
  @else if $name == "baz" { ... }
  // ... much much more characters ...

  &:before {
    content:"#{$glyph}";
  }

  /* aggreagation of selectors ? */
}

@function selectorsUsingFontcustom() {
  /* this should somehow result in a list of selectors, see above */
  font-family: fontcustom;
  color: red;
  /* ... */
}

显然还需要更多样式声明,例如font-family,colors等。

我想避免重复声明所以我的问题是:有没有办法让mixin“记住”导致应用它的选择器并生成逗号分隔的列表,这导致类似下面的内容?

SCSS:

#my-fancy-selector [data-is-liked] {
  @include fontcustom("heart");
}
.another>.fancy+.foo-selector {
  @include fontcustom("foo");
}

.another>.fancy+.baz-selector {
  @include fontcustom("baz");
}

/* no clue about the following: */
selectorsUsingFontcustom();

CSS:

#my-fancy-selector [data-is-liked]:before {
  content:"\2764";
}

.another>.fancy+.foo-selector:before {
  content:"\2765";
}

.another>.fancy+.baz-selector:before {
  content:"\2767";
}

/* selectorsUsingFontcustom() should return sth like the following then: */
#my-fancy-selector [data-is-liked]:before,
.another>.fancy+.foo-selector:before,
.another>.fancy+.baz-selector:before {
  font-family: fontcustom;
  color: red;
  /* ... */
} 

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

@extend与占位符选择器一起使用,如下所示:

%heart {
  color: red;
}

h1 {
  @extend %heart;
  font-size: 3em;
}

h2 {
  @extend %heart;
  font-size: 2em;
}

li {
  @extend %heart;
  text-decoration: strikethrough;
}

输出:

h1, h2, li {
  color: red;
}

h1 {
  font-size: 3em;
}

h2 {
  font-size: 2em;
}

li {
  text-decoration: strikethrough;
}