1,实现黑暗模式主要是对css变量的抽取和全局css的替换

2,编写一个全局的css变量css文件

:root{
  --page-bg-color: #fff;
  --head-bg-color: rgba(255, 255, 255, 0.7);
  --text-color:rgba(0, 0, 0, 0.85);
  --line-color: #e8e8e8;
  --content-bg-color:#f0f2f5;
}

3,创建dark.less和light.less文件对应黑暗和白天

dark.less 

@import "../../node_modules/ant-design-vue/dist/antd.dark.less";
@import "./index.css";
@import "./base.less";
@import "./vars.css";

light.less 

@import "../../node_modules/ant-design-vue/dist/antd.less";
@import "./index.css";
@import "./base.less";
@import "./vars.css";

4,在less和css中用变量替换掉原本的数值

.pagemodal {
  background: white;
  background: var(--page-bg-color);
  border-radius: 5px;
  padding: 10px;
}

5,编写切换css函数

// 切换css
export const changeTheme = (theme: string) => {
  const head = document.head;
  document.getElementById("theme")?.remove();
  const styleDom = document.createElement("style");
  styleDom.id = "theme";
  styleDom.innerHTML = theme;
  head.appendChild(styleDom);
};
 
// 改变css变量
export const changeCss = (css: string, value: string) => {
  const body = document.body.style;
  body.setProperty(css, value);
};

6,编写一个切换黑暗白天模式的函数

//引入ant design vue的css 白色和黑色的less文件都要引入
import light from "../less/light.less";
import dark from "../less/dark.less";
// 切换黑暗模式或者白天模式
export const DarkMode = (isDark: boolean) => {
  if (isDark) {
    changeTheme(dark);
    changeCss("--page-bg-color", "#141414");
    changeCss("--head-bg-color", "rgba(0, 0, 0, 0.5)");
    changeCss("--line-color", "#2e2e2e");
    changeCss("--content-bg-color", "rgb(255 255 255 / 4%)");
    changeCss("--text-color", "rgba(255, 255, 255, 0.85)");
  } else {
    changeTheme(light);
    changeCss("--page-bg-color", "white");
    changeCss("--head-bg-color", "rgba(255, 255, 255, 0.7)");
    changeCss("--line-color", "#e8e8e8");
    changeCss("--content-bg-color", "#f0f2f5");
    changeCss("--text-color", "rgba(0, 0, 0, 0.85)");
  }
};

7,使用的时候只要

// 白色
DarkMode(false);
 
// 黑色
DarkMode(true);


 

Logo

前往低代码交流专区

更多推荐