更改变量值 scss

Reg*_*mer 8 themes sass angular

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

_variables.scss

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

如何定义 3 组主题?就像是:

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;
}
Run Code Online (Sandbox Code Playgroud)

我想根据选定的主题更改值。例如我有 3 个按钮,在它们上选择,将改变可变颜色。

应用程序组件.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>
Run Code Online (Sandbox Code Playgroud)

app.component.ts

  onSetTheme(theme) {
    //TODO here I want to change the theme
  }
Run Code Online (Sandbox Code Playgroud)

如何更改 onSetTheme() 函数内的主题。

谢谢!

mii*_*iir 9

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

Sass 是 CSS 的预处理器,可以让您在开发过程中更轻松地编写样式规则。浏览器不会加载您的 .scss/.sass 文件;它将加载 CSS —— 因此您的 .scss/.sass 必须转换为浏览器的 CSS。

您的 Sass 变量只是 Sass 文件中的变量。一旦转换为 CSS,变量将被替换为它们在编译时表示的值。

.scss 正在开发中:

body {
    background: $dark-theme;
}
Run Code Online (Sandbox Code Playgroud)

浏览器加载的已编译 CSS:

body {
    background: black;
}
Run Code Online (Sandbox Code Playgroud)

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


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

切换 CSS 类

CSS 变量 ( MDN )


Phi*_*hou 7

您可以将 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;
}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)