简体   繁体   English

根据暗或亮模式更改styles

[英]Change styles based on dark or light mode

I want to have a dark and a light theme on my Vue app.我想在我的 Vue 应用程序上有一个深色和浅色的主题。 I can create dark.scss file and change classes styles and use !important property to override styles defined in components.我可以创建dark.scss文件并更改类 styles 并使用!important属性覆盖在组件中定义的 styles。 Or I can use props in my components and change className with v-if based on the theme.或者我可以在我的组件中使用props ,并根据主题使用v-if更改 className。 eg set class to className__light when theme is light otherwise set to className__dark .例如,当主题为浅色时将 class 设置为className__light ,否则设置为className__dark which one is better in all situations like performance or time needed to do it?在所有情况下,例如性能或所需时间,哪一个更好?

Well i would not do it with classes.好吧,我不会在课堂上这样做。 I would create CSS variables with either SCSS or you create CSS variables in :root我将使用 SCSS 创建 CSS 变量,或者您在:root中创建 CSS 变量

If you do it with the :root method then it should look something like this:如果您使用:root方法执行此操作,那么它应该如下所示:

:root {
   --background: red;
}

Then you can access it in any component like this for example:然后您可以在任何组件中访问它,例如:

.class {
   background: var(--background); // the background will appear red
}

Now you can change the background color with just 1 CSS variables.现在您只需 1 个 CSS 变量即可更改背景颜色。

To change the variable with Javascript you just write following:要使用 Javascript 更改变量,您只需编写以下内容:

 root.style.setProperty('--background', "green");

The problem here is that it isnt supported in IE if you care about browser support.这里的问题是,如果您关心浏览器支持,则 IE 不支持它。 So you should create an fallback like this:所以你应该像这样创建一个后备:

.class {
   background: red; //fallback
   background: var(--background); // the background will appear red
}

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

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