没有。您所要求的将需要 Sass 了解 DOM。 Sass 只直接编译成 CSS,它从不发送到浏览器。
使用您的示例代码,您所做的只是每次都覆盖$basicFont。在 3.4 或更高版本中,您的变量将仅存在于设置它的块的范围内。
因此,您唯一真正的选择是使用 mixins 或扩展。
扩展
这是有效的,但只适用于非常简单的情况。
%font-family {
&.one {
font-family: Verdana, sans-serif;
}
&.two {
font-family: Tahoma, sans-serif;
}
}
.foo {
@extend %font-family;
}
输出:
.one.foo {
font-family: Verdana, sans-serif;
}
.two.foo {
font-family: Tahoma, sans-serif;
}
混音
如果您想要更细粒度地控制在何处使用哪些变量,这是我推荐的方法。
$global-themes:
( '.one': ('font-family': (Verdana, sans-serif), 'color': red)
, '.two': ('font-family': (Tahoma, sans-serif), 'color': blue)
);
$current-theme: null; // don't touch, this is only used by the themer mixin
@mixin themer($themes: $global-themes) {
@each $selector, $theme in $themes {
$current-theme: $theme !global;
&#{$selector} {
@content;
}
}
}
@function theme-value($property, $theme: $current-theme) {
@return map-get($theme, $property);
}
.foo {
@include themer {
font-family: theme-value('font-family');
a {
color: theme-value('color');
}
}
}
输出:
.foo.one {
font-family: Verdana, sans-serif;
}
.foo.one a {
color: red;
}
.foo.two {
font-family: Tahoma, sans-serif;
}
.foo.two a {
color: blue;
}