我正试图在SASS(运行3.2.3 )中找到一种方法来捕获已解析的父选择器(&
),可能是在mixin中。
不幸的是(我在github上发现了对此的讨论)以下的解决方案不起作用:
@mixin append-to-captured-parent($append) {
$selector: "&-#{$append}";
#{$selector} { @content; }
}
.foo {
@include append-to-captured-parent("bar") {
color: blue;
}
}
所需的输出是:
.foo .foo-bar { color: blue; }
是否有任何黑客或解决方法可以产生所需的输出?据我所知,这可能是不可能的,因为在SASS解析器构造完整个节点树之前,父解析器不会被解析,此时它会遇到&-bar { ... }
,它就会死掉:
Syntax error: Invalid CSS after "&": expected "{", was "-bar"
我们可以欺骗SASS先发制人地解决这个问题吗?
注意:我不仅对SASS扩展( Ruby libs )持开放态度,而且可以实现这一目标。不幸的是,在这个时候,我并不是足够精通Ruby的人(我正在研究它)
答案 0 :(得分:1)
好吧,我想出了一个解决方法。
此方法仅隔离预期的功能,并独立于实际层次结构进行管理。
首先,一些快速实用程序:
@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"; }