我有一个@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;
}但是,当我尝试这样做时,会遇到以下错误:
在./lib/all.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./lib/all.scss)中出错 模块构建失败(来自./node_ Module /sass-加载程序/lib/loader.js):
@include pre(.bar + .baz) { ^无效的CSS在"@include pre(“)之后:预期表达式(例如,1 1px,粗体),was”.p-pre){。“
我怀疑这与$list_separator有关,但我不知道如何实现这一点。有人知道如何做到这一点吗?
发布于 2019-05-06 01:34:58
如果您真的觉得不需要使用字符串,可以将运算符放到一个映射中;演示
代码
$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;
}发布于 2019-05-06 01:15:21
是的,操作人员需要是字符串。但是您可以不带字符串地传递选择器。演示
代码
$pre: ;
@mixin namespace($args...) {
$selector: '';
@each $val in $args {
$index: index($args, $val);
$selector: $selector + if($index % 2 == 1, '.#{$pre}-#{$val}', ' #{$val} ');
}
#{$selector} {
@content
}
}用法
@include namespace(cool, '+', stuff) {
color: green;
}
@include namespace(stuff, '~', things) {
color: red;
}
@include namespace(stuff, '*:not(.lame)', things) {
color: red;
}https://stackoverflow.com/questions/55757768
复制相似问题