0

我试图弄清楚是否有可能组合 mixin 选择器字符串。我不相信这在我的代码上下文中是可能的,但我很可能会遗漏一些东西!

假设我有以下scss:

// Apply a set of rules to input form fields.
@mixin input-form-fields {
    input:not([type="hidden"]),
    textarea {
        @content;
    }
}

// Apply a set of rules to button form fields.
@mixin button-form-fields {
    button, button {
        @content;
    }
}

// Apply a set of rules to select form fields.
@mixin select-form-fields {
    select {
        @content;
    }
}

// Apply a set of rules to all form fields.
@mixin all-form-fields {
    @include input-form-fields {
        @content;
    }
    @include button-form-fields {
        @content;
    }
    @include select-form-fields {
        @content;
    }
}

基本上 all-form-fields mixin 将调用其他 mixin,从而为不同的选择器生成相同的规则集。

如果我编译以下代码:

@include all-form-fields {
    margin-bottom: .5em;
}

我会得到类似的东西:

input:not([type="hidden"]),
textarea {
  margin-bottom: .5em;
}

button, 
.button {
  margin-bottom: .5em;
}

select {
  margin-bottom: .5em;
}

这并不理想,如果我可以组合这些选择器,我会喜欢的。

有没有人对我如何组合由 3 个不同的 mixin 返回的选择器字符串有任何想法?

4

1 回答 1

2

如果您不介意将选择器存储在字符串中,则可以使用变量定义不同的字段类型:

$input-form-fields: "input:not([type=hidden]), textarea";
$button-form-fields: "button";
$select-form-fields: "select";

然后,您使用插值字符串定义您的 mixins,如下所示:

// Apply a set of rules to input form fields.
@mixin input-form-fields {
    #{$input-form-fields} {
        @content;
    }
}

// Apply a set of rules to button form fields.
@mixin button-form-fields {
    #{$button-form-fields} {
        @content;
    }
}

// Apply a set of rules to select form fields.
@mixin select-form-fields {
    #{$select-form-fields} {
        @content;
    }
}

// Apply a set of rules to all form fields.
@mixin all-form-fields {
    #{$input-form-fields}, 
    #{$button-form-fields}, 
    #{$select-form-fields} {
        @content;
    }
}

结果,@include all-form-fields将导致

input:not([type=hidden]), textarea,
button,
select {
  margin-bottom: .5em; }
于 2013-08-13T16:47:19.937 回答