首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SASS和数据属性的选择和嵌套

SASS和数据属性的选择和嵌套
EN

Stack Overflow用户
提问于 2014-08-19 00:25:40
回答 2查看 24.5K关注 0票数 7

我想将一些样式应用于具有数据属性product的元素,但也适用于特定于产品。

有办法做这样的事吗?

代码语言:javascript
复制
// SASS
[data-product] {
  color: #000;
  &[="red"] {   // <- this line
    color: #f00;
  }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-08-19 01:03:28

在Sass 3.4之前,这一点根本不可能。这里的关键特性是将当前选择器存储到变量中的能力和拆分字符串的能力(尽管后者可以通过SassScript函数创建)。

代码语言:javascript
复制
@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;
    }
}

用法:

代码语言:javascript
复制
[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;
    }
}

输出:

代码语言:javascript
复制
[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;
}

相关:Modifying the middle of a selector in Sass (adding/removing classes, etc.)

票数 13
EN

Stack Overflow用户

发布于 2015-11-01 09:28:15

代码语言:javascript
复制
input[data-product] {
	color: #000;
}
input[data-product=red] {
	color: #f00;
}

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

票数 -3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25373991

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档