我有一个@mixin
允许我命名空间选择器。代码如下:
@mixin pre-assign($value) {
$pre: $value !global;
}
@include pre-assign('foo');
@function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace +
str-replace(
str-slice($string, $index + str-length($search)),
$search,
$replace
);
}
@return $string;
}
@mixin pre($value) {
$result: '';
$result: str-replace($value, '.', '.#{$pre}-');
#{$result} {
@content;
}
}
我可以按如下方式使用@mixin
:
// declaration
@include pre('.bar + .baz') {
display: none;
}
// output
.foo-bar + .foo-baz {
display: none;
}
我想整理一下将选择器传递给 @mixin
并省略引号的方式,这样我就不会将选择器作为字符串值传递:
@include pre(.bar + .baz) {
display: none;
}
但是,当我尝试这样做时,遇到了以下错误:
ERROR in ./lib/all.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./lib/all.scss)
Module build failed (from ./node_modules/sass-loader/lib/loader.js):
@include pre(.bar + .baz) { ^
Invalid CSS after "@include pre(": expected expression (e.g. 1px, bold), was ".p--compact) {"
我怀疑这与 $list_separator
有关,但我不确定如何实现。有谁知道如何实现这一点?
最佳答案
如果你真的觉得不需要使用字符串,你可以把你的运算符放在一个映射中; DEMO
代码
$operators: (
adjacent: '+',
general: '~',
universal: '*',
child: '>',
descendent: ' '
);
@mixin namespace($list...) {
$selector: '';
@each $arg in $list {
$index: index($list, $arg);
$val: if($index % 2 == 1, '.#{$pre}-#{$arg}', map-get($operators, $arg));
$selector: $selector + $val;
}
#{$selector} {
@content
}
}
用法
@include namespace(cool, adjacent, stuff) {
color: green;
}
@include namespace(cool, general, stuff) {
color: green;
}
关于css - Sass 列表分隔符并写一个干净的@mixin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55757768/