0

我试图让一个 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;
  /* ... */
}

显然还需要更多的样式声明,例如字体系列、颜色等。

我想避免重复声明,所以我的问题是:有没有办法让 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;
  /* ... */
} 

有任何想法吗?

4

1 回答 1

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;
}
于 2013-05-03T20:40:23.953 回答