SASS 和数据属性选择和嵌套 [英] SASS and Data Attribute Selecting and Nesting
本文介绍了SASS 和数据属性选择和嵌套的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想对具有数据属性 product
的元素以及特定产品应用一些样式.
I would like to apply some style to elements with the data attribute product
but also to specific products.
有没有办法做这样的事情?
// SASS
[data-product] {
color: #000;
&[="red"] { // <- this line
color: #f00;
}
}
推荐答案
在 Sass 3.4 之前,这是根本不可能的.这里的突破性功能是能够将当前选择器存储到一个变量中以及拆分字符串的能力(尽管后者可以通过 SassScript 函数创建).
Prior to Sass 3.4, this is just not possible at all. The deal-breaking features here are the ability to store the current selector into a variable and the ability to split a string (though the later could be created via SassScript functions).
@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 和数据属性选择和嵌套的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文