如何通过css变量实现主题切换?
文章目录
目的
采用css变量来切换应用的主题。
手段
1 定义好主题需要的css变量
/* theme.css */
.light {
--custom-background: white;
}
.dark {
--custom-background: black;
}2 全局引入上面定义的css变量
/* index.js */
import './theme.css';3 实现切换主题class的逻辑
/* App.js */
document.documentElement.className = 'light';
or
document.documentElement.className = 'dark';4 在应用中各个位置引用全局引入的css变量
/*app.css*/
body {
background: var(--theme-background);
}这样,当html元素的class在light和dark之间切换时,css变量--custom-background的值也会在white和black之间切换,至此,完成css变量的主题切换。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论