0

我正在尝试找到一种方法来&在 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 库)持开放态度;不幸的是,此时我还不够精通 Ruby,无法自己动手(不过我正在努力

4

1 回答 1

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"; }
于 2013-03-23T17:05:46.330 回答