简体   繁体   English

如何使用SASS动态切换颜色主题?

[英]How to dynamically switch color themes using SASS?

I'm trying to implement switchable themes for a project, it's a Mendix project, but let's suppose it's a website.我正在尝试为一个项目实现可切换的主题,它是一个 Mendix 项目,但让我们假设它是一个网站。

  • There are many different pages, and different elements on each page.有许多不同的页面,每个页面上都有不同的元素。
  • All styles for them are written in SASS.它们的所有样式都是用 SASS 编写的。 The pages and elements use values from one separate SASS file with variables - variables-1 .页面和元素使用来自一个带有变量的单独 SASS 文件的值 - variables-1
  • I have a second SASS file with the same variables but different values - variables-2 .我有第二个具有相同变量但值不同的 SASS 文件 - variables-2

Problem:问题:
I need to change the color theme of the website on a button click.我需要通过单击按钮更改网站的颜色主题。 So basically I need all the elements to take colors from the different set of variables when I click a button.所以基本上我需要所有元素在我单击按钮时从不同的变量集中获取颜色。


I see two options here:我在这里看到两个选项:

  1. Compile 2 css files and switch between them: link all sass files to variables-1 , compile CSS file, then link all sass files to variables-2 , compile second css file.编译 2 个 css 文件并在它们之间切换:将所有 sass 文件链接到variables-1 ,编译 CSS 文件,然后将所有 sass 文件链接到variables-2 ,编译第二个 css 文件。 Switch between them on a button click.单击按钮即可在它们之间切换。

    In this option, colors won't be assigned dynamically, and every time when I make changes I will have to manually link each sass file to different variables, or change variables values, and recompile everything.在此选项中,颜色不会动态分配,每次进行更改时,我都必须手动将每个 sass 文件链接到不同的变量,或更改变量值,然后重新编译所有内容。 Also I won't be able to continue working on the project and switch themes at the same time.此外,我将无法继续处理该项目并同时切换主题。

  2. Predefine color themes in mixins, compile css classes for each theme like in this article , and use some custom js logic to assign corresponding classes to the elements.在 mixins 中预定义颜色主题,像本文一样为每个主题编译 css 类,并使用一些自定义 js 逻辑为元素分配相应的类。

    Most likely won't work, since there are too many elements in the project, and would be too complicated to change class for each one.很可能不会起作用,因为项目中的元素太多,并且为每个元素更改类太复杂了。

How can I solve this problem?我怎么解决这个问题?

You can't dynamically change sass variables in the browser.您不能在浏览器中动态更改 sass 变量。 Here is a more detailed explanation:这里有更详细的解释:

Changing variables values scss 更改变量值 scss

A possible solution for you is to add or remove a class to the body that represents the theme.一个可能的解决方案是向代表主题的正文添加或删除一个类。 Then, for example, if body has class "dark-theme", background color is black and so on.然后,例如,如果 body 具有类“dark-theme”,则背景颜色为黑色等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM