css变量(主题切换)

css文件

1
2
3
4
5
6
:root.light {
--background--main: rgba(245, 245, 245, 1);
}
:root.dark {
--background--main: rgba(15, 15, 15, 1);
}body {background-color: var(--background--main);}

:root 这个 CSS 伪类匹配文档树的根元素。对于 HTML 来说,:root 表示 <html> 元素,除了优先级更高之外,与 html 选择器相同。

 html文件

1
2
3
4
5
6
<html lang="en" class="light">
  <head>
    <meta charset="utf-8" />
  </head>
  <body>1</body>
</html>

js文件

1
2
3
4
5
6
7
8
9
const html = document.querySelector(':root');
// 获取--background--main变量的内容
console.log(getComputedStyle(html).getPropertyValue('--background--main'));
setTimeout(() => {
    // 设置html也就是:root的class为dark
    html.className = 'dark';
    // 获取--background--main变量的内容
    console.log(getComputedStyle(html).getPropertyValue('--background--main'));
}, 1000);

  

posted @   瑞瑞大人  阅读(183)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示