不需要。您要求的內容需要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;
}