SCSS从@if内部改变变量超出范围

时间:2013-05-24 19:22:35

标签: sass

当您想要修改函数范围之外的变量时,是否有针对该情况的解决方法? :

$ui-theme: 'pink';

@if $ui-theme == "pink" {
    $ui-main: #eb82b0;  
    $ui-secondary: #fff5f9;
    $ui-third: #f6c2d9;
} @else {
    $ui-main: #ff8067;  
    $ui-secondary: #fff6e5;
    $ui-third: #ffb1a2;
}

a { color: $ui-main; background: $ui-secondary };

我想创建一个名为ui-theme的全局变量,它将在定义下面的所有其他代码中定义$ui-main, $ui-secondary...。似乎在使用@if等指令时也会应用变量范围。

有谁知道如何实现这一目标?

1 个答案:

答案 0 :(得分:3)

您必须在控制块之外初始化变量:

$ui-theme: 'pink';

$ui-main: null;
$ui-secondary: null;
$ui-third: null;

@if $ui-theme == "pink" {
    $ui-main: #eb82b0;  
    $ui-secondary: #fff5f9;
    $ui-third: #f6c2d9;
} @else {
    $ui-main: #ff8067;  
    $ui-secondary: #fff6e5;
    $ui-third: #ffb1a2;
}

a { color: $ui-main; background: $ui-secondary };

输出:

a {
  color: #eb82b0;
  background: #fff5f9;
}

通过@include进行主题化而不是像这样的硬编码变量可能更好。

_pink.scss:

$ui-main: #eb82b0;  
$ui-secondary: #fff5f9;
$ui-third: #f6c2d9;

styles.scss:

@include "pink"; // or don't include anything if you want the default colors

$ui-main: #ff8067 !default;
$ui-secondary: #fff6e5 !default;
$ui-third: #ffb1a2 !default;

a { color: $ui-main; background: $ui-secondary };