自学内容网 自学内容网

vue3实现自定义主题色切换功能

1.添加theme样式文件

在这里插入图片描述
文件内容如下:

html[data-theme="light"]{
  --text-color: #000000;
  /* 写需要切换的样式 */
}
html[data-theme="dark"]{
  --text-color: #ffffff;
  /* 写需要切换的样式 */
}

2.引入样式文件

在main.js中引入文件:

import './styles/theme.css'

3.使用变量设置css样式

使用var(自定义的变量名)来设置动态的css样式

.text {
  color: var(--text-color);
 }

4.设置主题样式

在index.html文件里设置默认样式
在这里插入图片描述

5.切换方法

<button @click="changeTheme">切换</button>
const theme = ref('dark')
const changeTheme = () =>{
document.documentElement.setAttribute("data-theme", theme.value == "dark" ? "light" : "dark")
theme.value = theme.value == 'dark' ? 'light' : 'dark'
}

原文地址:https://blog.csdn.net/qq_39981639/article/details/142551069

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!