我想知道是否可以根据是否设置类在 Sass 中定义变量。我需要做一些字体类型测试,并想根据主体类动态更改字体变量 $basicFont
。
例如:
$basicFont: Arial, Helvetica, sans-serif;
body {
&.verdana {
$basicFont: Verdana, sans-serif;
}
&.tahoma {
$basicFont: Tahoma, sans-serif;
}
}
有没有可能在 Sass 中处理这个问题?
最佳答案
没有。您要求的内容需要 Sass 了解 DOM。 Sass 只直接编译成 CSS,它永远不会发送到浏览器。
使用您的示例代码,您所做的就是每次都覆盖 $basicFont
。在 3.4 或更高版本中,您的变量将仅存在于设置它的 block 的范围内。
因此,您唯一真正的选择是使用混合或扩展。
扩展
这是有效的,但只适用于非常简单的情况。
%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;
}
关于sass - 基于类在 Sass 中定义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30057873/