SASS和数据属性选择器以及嵌套

8
我希望能对具有data属性product的元素应用一些样式,但也要针对特定的产品进行处理。 是否有类似这样的方法呢?
// SASS
[data-product] {
  color: #000;
  &[="red"] {   // <- this line
    color: #f00;
  }
}
2个回答

14

在 Sass 3.4 之前,这根本不可能。 至关重要的功能是能够将当前选择器存储到变量中以及拆分字符串的能力(尽管后者可以通过 SassScript 函数创建)。

@mixin append-attr($x) {
    $sel: &;
    $collector: ();

    @for $i from 1 through length($sel) {
        $s: nth($sel, $i);
        $last: nth($s, -1);
        @if str-slice($last, -1) == "]" {
            // if is just the bare attribute with no value, $offset will be -1, otherwise it will be -2
            $offset: -1;
            $current-x: $x;

            @if str-slice($last, -2) == '"]' {
                // this attribute already has a value, so we need to adjust the offset
                $offset: -2;
            } @else {
                // no attribute value, so add the equals and quotes
                $current-x: '="' + $x + '"';
            }
            $last: str-slice($last, 1, $offset - 1) + $current-x + str-slice($last, $offset);
            $collector: append($collector, set-nth($s, -1, $last), comma);
        } @else {
            // following line will append $x to your non-attribute selector
            $collector: append($collector, selector-append($s, $x), comma);
            // the following line will not change your non-attribute selector at all
            //$collector: append($collector, $s, comma);
        }
    }

    @at-root #{$collector} {
        @content;
    }
}

使用方法:

[data-product] {
    color: white;

    @include append-attr("red") {
        color: red;

        @include append-attr('-green') {
            color: green;
        }
    }
}

[one], [two] {
    color: orange;

    @include append-attr('alpha') {
        color: yellow;
    }
}

[test], .test {
    @include append-attr('-one') {
        color: red;
    }
}

.bar input[min] {
    @include append-attr('5') {
        background: yellow;
    }
}

输出:

[data-product] {
  color: white;
}
[data-product="red"] {
  color: red;
}
[data-product="red-green"] {
  color: green;
}

[one], [two] {
  color: orange;
}
[one="alpha"], [two="alpha"] {
  color: yellow;
}

[test="-one"], .test-one {
  color: red;
}

.bar input[min="5"] {
  background: yellow;
}

相关内容: 如何在Sass中修改选择器的中间部分(添加/删除类等)


-1

input[data-product] {
 color: #000;
}
input[data-product=red] {
 color: #f00;
}

您不需要嵌套,第二个样式将覆盖第一个。


这怎么能算是对问题的回答呢?问题的重点在于能够编写一个更短的选择器。 - cimmanon
1
这对我来说是第一次搜索非常有帮助的。 - ariel guzman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接