使用SASS映射而不是变量实际上可以做到这一点。这是一个简单的示例:
动态引用:
$colors: (
blue: #007dc6,
blue-hover: #3da1e0
);
@mixin colorSet($colorName) {
color: map-get($colors, $colorName);
&:hover {
color: map-get($colors, $colorName#{-hover});
}
}
a {
@include colorSet(blue);
}
输出为:
a { color:#007dc6 }
a:hover { color:#3da1e0 }
动态创建:
@function addColorSet($colorName, $colorValue, $colorHoverValue: null) {
$colorHoverValue: if($colorHoverValue == null, darken( $colorValue, 10% ), $colorHoverValue);
$colors: map-merge($colors, (
$colorName: $colorValue,
$colorName#{-hover}: $colorHoverValue
));
@return $colors;
}
@each $color in blue, red {
@if not map-has-key($colors, $color) {
$colors: addColorSet($color, $color);
}
a {
&.#{$color} { @include colorSet($color); }
}
}
输出为:
a.blue { color: #007dc6; }
a.blue:hover { color: #3da1e0; }
a.red { color: red; }
a.red:hover { color: #cc0000; }