好吧,我想出了一个变通办法。
这种方法只是隔离了预期的功能,并独立于实际层次结构对其进行管理。
首先,一些快速实用程序:
@function slice($list, $from, $into) {
$result: ();
@for $index from $from through $into {
$result: append($result, nth($list, $index));
}
@return $result;
}
@function implode($list, $separator) {
$result: nth($list, 1);
@for $index from 2 through length($list) {
$result: #{$result}#{$separator}#{nth($list, $index)};
}
@return $result;
}
然后是胆子:
$-class: ();
@function get-class() {
$top: if(length($-class) - 2 < 1, 1, length($-class) - 2);
@return implode(slice($-class, $top, length($-class)), "-");
}
@mixin class($name) {
$-class: append($-class, $name);
.#{get-class()} {
@content;
}
$-class: slice($-class, 1, length($-class) - 1);
}
这里发生的是,“全局”变量$-class
在每次调用 mixin 时维护一个嵌套堆栈class
。它通过内爆堆栈上的前三个名称来创建 CSS 类声明(如果需要,可以将其修改为完整堆栈)
所以复制问题的例子:
@include class (foo) {
color: red;
@include class (bar) {
color: blue;
}
}
将产生:
.foo { color: red; }
.foo .foo-bar { color: blue; }
一个不那么简单的例子是:
@include class(list) {
test: "list";
@include class(item) {
test: "item";
@include class(heading) {
test: "heading";
}
@include class(content) {
test: "content";
@include class(graphic) {
test: "graphic";
}
@include class(summary) {
test: "summary";
}
@include class(details) {
test: "details";
}
}
@include class(footing) {
test: "footing";
}
}
}
生产:
.list { test: "list"; }
.list .list-item { test: "item"; }
.list .list-item .list-item-heading { test: "heading"; }
.list .list-item .list-item-content { test: "content"; }
.list .list-item .list-item-content .item-content-graphic { test: "graphic"; }
.list .list-item .list-item-content .item-content-summary { test: "summary"; }
.list .list-item .list-item-content .item-content-details { test: "details"; }
.list .list-item .list-item-footing { test: "footing"; }