我不知道 Sass 是否能够做到这一点,但问一下也无妨。
问题
基本上我有在应用程序的多个部分重复的三种颜色模式,如 blue
, green
和 orange
.有时变化的是background-color
,或 border-color
组件的...有时是文本 color
子元素等
我怎么想的?
1. 替换内容中的字符串模式。
.my-class {
@include colorize {
background-color: _COLOR_;
.button {
border-color: _COLOR_;
color: _COLOR_;
}
}
}
2. 为
@content
提供回调变量.// This is just a concept, IT DOESN'T WORK.
@mixin colorize {
$colors: blue, green, orange;
@each $colors in $color {
// ...
@content($color); // <-- The Magic?!
// ...
}
}
// Usage
@include colorize {
background-color: $color;
}
I tried to implement such solutions, but without success.
取而代之的是...
请参阅下面我的解决方法以使其部分工作:
@mixin colorize($properties) {
$colors: blue, green, orange;
@for $index from 1 through length($colors) {
&:nth-child(#{length($colors)}n+#{$index}) {
@each $property in $properties {
#{$property}: #{nth($colors, $index)};
}
}
}
}
你可以这样使用这个 mixin:
.some-class {
@include colorize(background-color);
}
会输出什么:
.some-class:nth-child(3n+1) {
background-color: blue;
}
.some-class:nth-child(3n+2) {
background-color: green;
}
.some-class:nth-child(3n+3) {
background-color: orange;
}
The problem? Well, I can't use it with child selectors.
根据以上信息,对于这种情况有什么神奇的解决方案吗?
最佳答案
我想我明白你的意思了;它有点(非常)凌乱,但它应该做你想做的:
@mixin colorize($parentProperties,$childMaps) {
$colors: blue, green, orange;
@for $index from 1 through length($colors) {
&:#{nth($colors, $index)} {
@each $property in $parentProperties {
#{$property}: #{nth($colors, $index)};
}
}
@each $mapped in $childMaps {
$elem: nth($mapped,1);
$properties: nth($mapped,2);
#{$elem}:nth-child(#{length($colors)}n+#{$index}) {
@each $property in $properties {
#{$property}: #{nth($colors, $index)};
}
}
}
}
}
结果是:
/* -------------- USAGE ------------------*/
.some-class {
@include colorize(
background-color,( //Parent properties
(button, background-color), //Child, (properties)
(span, (background-color,border-color)) //Child, (properties)
)
);
}
/* --------------- OUTPUT ----------------*/
.some-class:nth-child(3n+1) {
background-color: blue;
}
.some-class button:nth-child(3n+1) {
background-color: blue;
}
.some-class span:nth-child(3n+1) {
background-color: blue;
border-color: blue;
}
.some-class:nth-child(3n+2) {
background-color: green;
}
.some-class button:nth-child(3n+2) {
background-color: green;
}
.some-class span:nth-child(3n+2) {
background-color: green;
border-color: green;
}
.some-class:nth-child(3n+3) {
background-color: orange;
}
.some-class button:nth-child(3n+3) {
background-color: orange;
}
.some-class span:nth-child(3n+3) {
background-color: orange;
border-color: orange;
}
希望这就是你要找的:)
关于Sass Mixin : Callback or Replace @content,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37128950/