根据深色或浅色模式更改样式 [英] Change styles based on dark or light mode

查看:35
本文介绍了根据深色或浅色模式更改样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 Vue 应用程序上有一个深色和一个浅色的主题.我可以创建 dark.scss 文件并更改类样式并使用 !important 属性来覆盖组件中定义的样式.或者我可以在我的组件中使用 props 并根据主题使用 v-if 更改 className.例如当主题为浅色时,将 class 设置为 className__light,否则设置为 className__dark.哪一个在所有情况下都更好,比如性能或完成它所需的时间?

I want to have a dark and a light theme on my Vue app. I can create dark.scss file and change classes styles and use !important property to override styles defined in components. Or I can use props in my components and change className with v-if based on the theme. e.g. set class to className__light when theme is light otherwise set to className__dark. which one is better in all situations like performance or time needed to do it?

推荐答案

好吧,我不会用类来做.我会使用 SCSS 创建 CSS 变量,或者您在 :root

Well i would not do it with classes. I would create CSS variables with either SCSS or you create CSS variables in :root

如果你使用 :root 方法,那么它应该看起来像这样:

If you do it with the :root method then it should look something like this:

:root {
   --background: red;
}

然后您可以在任何组件中访问它,例如:

Then you can access it in any component like this for example:

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

现在您只需使用 1 个 CSS 变量即可更改背景颜色.

Now you can change the background color with just 1 CSS variables.

要使用 Javascript 更改变量,您只需编写以下内容:

To change the variable with Javascript you just write following:

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

这里的问题是,如果您关心浏览器支持,IE 不支持它.所以你应该像这样创建一个后备:

The problem here is that it isnt supported in IE if you care about browser support. So you should create an fallback like this:

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

这篇关于根据深色或浅色模式更改样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆