简化 sass 属性选择器
Simplifying sass attribute selectors
我正在尝试想出一种方法来简化某些 SCSS 属性选择器。我最终得到的是:
[data-attr="opt1"] { ... }
[data-attr="opt2"] { ... }
[data-attr="opt3"] { ... }
我希望能够写出更接近于:
的东西
[data-attr]
&="opt1" { ... }
&="opt2" { ... }
&="opt3" { ... }
通过mixin 或其他方式。虽然无法提出解决方案。有什么妙招吗?
我想到了这个想法:
@mixin attrVal($value) {
$attr: str-slice(#{&}, 2, -2); // $attr = "data-attr"
@at-root {
[#{$attr}="#{$value}"] {
@content;
}
}
}
[data-attr] {
@include attrVal('opt1') { width: 10px; }
@include attrVal('opt2') { width: 20px; }
@include attrVal('opt3') { width: 30px; }
}
输出(在 sassmeister.com 上测试)
[data-attr="opt1"] { width: 10px; }
[data-attr="opt2"] { width: 20px; }
[data-attr="opt3"] { width: 30px; }
对于这个特定的示例,没有那么大的简化,但是通过这种方法,您实际上将属性名称与其值分离(为了代码重用)。
我正在尝试想出一种方法来简化某些 SCSS 属性选择器。我最终得到的是:
[data-attr="opt1"] { ... }
[data-attr="opt2"] { ... }
[data-attr="opt3"] { ... }
我希望能够写出更接近于:
的东西[data-attr]
&="opt1" { ... }
&="opt2" { ... }
&="opt3" { ... }
通过mixin 或其他方式。虽然无法提出解决方案。有什么妙招吗?
我想到了这个想法:
@mixin attrVal($value) {
$attr: str-slice(#{&}, 2, -2); // $attr = "data-attr"
@at-root {
[#{$attr}="#{$value}"] {
@content;
}
}
}
[data-attr] {
@include attrVal('opt1') { width: 10px; }
@include attrVal('opt2') { width: 20px; }
@include attrVal('opt3') { width: 30px; }
}
输出(在 sassmeister.com 上测试)
[data-attr="opt1"] { width: 10px; }
[data-attr="opt2"] { width: 20px; }
[data-attr="opt3"] { width: 30px; }
对于这个特定的示例,没有那么大的简化,但是通过这种方法,您实际上将属性名称与其值分离(为了代码重用)。