更改变量值SCSS

9

我在我的scss文件中定义了不同的变量,并在一些scss文件中使用了这些变量。

_variables.scss

$light-theme: rgba(94,161,215,0.3);
$dark-theme: #5EA1D7;
$darker-theme: #57647A;
$very-dark-theme: #455061;

我该如何定义三组主题?就像这样:
default-theme {
    $light-theme: rgba(94,161,215,0.3);
    $dark-theme: #5EA1D7;
    $darker-theme: #57647A;
    $very-dark-theme: #455061;
}

dark-theme {
    $light-theme: black;
    $dark-theme: brown;
    $darker-theme: black;
    $very-dark-theme: black;
}

light-theme {
    $light-theme: black;
    $dark-theme: brown;
    $darker-theme: black;
    $very-dark-theme: black;
}

我可以帮助您进行翻译。以下是对所提供内容的翻译,保留了HTML标记:

我希望根据所选主题更改数值。 例如,我有3个按钮,选择它们之一会更改变量颜色。

app.component.html

 <button mat-raised-button (click)="onSetTheme('default-theme')">Default</button>
  <button mat-raised-button (click)="onSetTheme('dark-theme')">Dark</button>
  <button mat-raised-button (click)="onSetTheme('light-theme')">Light</button>

app.component.ts

  onSetTheme(theme) {
    //TODO here I want to change the theme
  }

如何在 onSetTheme() 函数中更改主题。

谢谢!


我正在使用Angular 4框架。 - Regina Kreimer
2个回答

9

为什么我们不能在浏览器中动态更改sass变量?

Sass是一种CSS预处理器,可使开发过程中编写样式规则更加简单。浏览器不会加载您的.scss/.sass文件;它将加载CSS -- 因此,必须将您的.scss/.sass转换为CSS以供浏览器使用。

您的Sass变量仅是Sass文件中的变量。一旦转换为CSS,这些变量将用它们在编译时所代表的值替换。

.scss在开发过程中:

body {
    background: $dark-theme;
}

浏览器加载的编译后的CSS:

body {
    background: black;
}

您的onSetTheme函数是一个JavaScript函数,将在浏览器中运行,并且无法访问更改Sass变量,因为它们此时不存在。浏览器仅加载已编译的CSS(不会加载原始的Sass文件和变量)。


如何在浏览器中动态更改网站主题?

切换CSS类

CSS变量 (mdn)


8

您可以同时使用SASS变量和其他SASS内容以及CSS变量。

SASS

$body-margin: 0 10px;

:root {
    --bg-color: #000;
    --text-color: #FFF;
}


body {
    background: var(--bg-color);
    color: var(--text-color;
    margin: $margin;
}

JS

onSetTheme(theme) {
    let bgColor, textColor;
    switch(theme) {
      case light:
          bgColor = #FFF;
          textColor = #000;
          break;
      case dark:
          bgColor = #000;
          textColor = #FFF;
          break;
    }
    document.querySelector('body').style.setProperty('--bg-color', bgColor);
    document.querySelector('body').style.setProperty('--text-color', textColor);
}

不支持IE - harsha reddy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接