当前位置:   article > 正文

纯css主题切换,简单易懂 document.documentElement.setAttribute(‘data-theme‘, ‘light‘);

document.documentelement.setattribute

假设你有两个css文件,放置主题颜色变量,需要主动引入页面中
vue的话 就是引入到main.js

/* 亮色模式 */
html[data-theme="light"]:root {
  --body-background: #efefef;
  --text-color:  #333;
  --primary-color: #3D79C4;
  --danger-color: #E3524E;
  --warning-color: #ffa94e;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
/* 深色模式 */
html[data-theme="dark"]:root {
  --body-background: #000;
  --text-color: #ededed;
  --primary-color: #ffa94e;
  --danger-color: #3D79C4;
  --warning-color: #FF0D41;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

之后所有用到颜色,且需要根据主题切换颜色的地方都需要写诸如:

background: var(--body-background);
  • 1

这时候随便找一个地方调用

document.documentElement.setAttribute('data-theme', 'light');
document.documentElement.setAttribute('data-theme', 'dark');
  • 1
  • 2

即可简单完成自配置样式的颜色切换。

实际实例
关于element-plus的颜色切换方案 可参考稀土掘金:
办法总比困难多

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/article/detail/84800
推荐阅读
相关标签
  

闽ICP备14008679号