父選擇器不能這樣使用,它只包含對前一個選擇器的引用。 Sass無法定位屬性選擇器的內容(至少,不在目前可用的任何字符串操作函數之外)。
您可以做的最好的方法是編寫自定義函數或使用內容感知混合來爲變量執行髒活。這裏是一個混合版本可能是什麼樣子(假設你想使用嵌套保持):
@mixin my-sel($append: false) {
$class: if($append, selector-append(&, $append), &);
@at-root a[class^="#{$class}"], a[class*=" #{$class}"] {
@content;
}
}
utility-button {
@include my-sel {
/* some shared css rules */
}
@include my-sel(-one) {
/* some unique css rules */
}
@include my-sel(-two) {
/* some unique css rules */
}
}
輸出:
a[class^="utility-button"], a[class*=" utility-button"] {
/* some shared css rules */
}
a[class^="utility-button-one"], a[class*=" utility-button-one"] {
/* some unique css rules */
}
a[class^="utility-button-two"], a[class*=" utility-button-two"] {
/* some unique css rules */
}
如果您需要能夠嵌套到這一點其他選擇,那麼它會相當多的更復雜:
@function class-to-attribute-selector($class) {
// the following line is completely optional, but you definitely need the @return
$class: if(str-index($class, '.') == 1, str-slice($class, 2), $class);
@return #{'[class^="#{$class}"]'}, #{'[class*=" #{$class}"]'};
}
@mixin class-sel {
$sel-list: &;
$new-sel:();
@each $sel in $sel-list {
@if length($sel) > 1 {
$s:();
@for $i from 1 to length($sel) {
$s: append($s, nth($sel, $i));
}
$class: nth($sel, length($sel));
$new-sel: append($new-sel, selector-nest($s, class-to-attribute-selector($class)));
} @else {
$new-sel: join($new-sel, class-to-attribute-selector(nth($sel, 1)));
}
}
@at-root #{$new-sel} {
@content;
}
}
.foo {
.utility-button {
@include class-sel {
/* some shared css rules */
}
&-one {
@include class-sel {
/* some unique css rules */
}
}
&-two {
@include class-sel {
/* some unique css rules */
}
}
}
}
.bar {
@include class-sel {
/* other rules */
}
}
輸出:
.foo [class^="utility-button"], .foo [class*=" utility-button"] {
/* some shared css rules */
}
.foo [class^="utility-button-one"], .foo [class*=" utility-button-one"] {
/* some unique css rules */
}
.foo [class^="utility-button-two"], .foo [class*=" utility-button-two"] {
/* some unique css rules */
}
[class^="bar"], [class*=" bar"] {
/* other rules */
}
相關:http://stackoverflow.com/questions/25373991/sass-and-data-attribute-selecting-and-nesting和http://stackoverflow.com/questions/28593476/appending-a-class-to-我選擇了一箇中間選擇器 – cimmanon
我喜歡按照第一個鏈接的數據屬性方法。我沒有真正考慮過使用數據屬性,但它看起來像一個體面的方法。 – AdamJB