uniapp主题更换
使用CSS变量实现主题切换
在uni.scss文件中定义全局CSS变量:
:root {
--primary-color: #007AFF;
--bg-color: #FFFFFF;
--text-color: #333333;
}
.dark-theme {
--primary-color: #0A84FF;
--bg-color: #1C1C1E;
--text-color: #F2F2F7;
}
在页面样式中使用这些变量:
.page {
background-color: var(--bg-color);
color: var(--text-color);
}
.button {
background-color: var(--primary-color);
}
动态切换主题类名
通过JavaScript动态切换HTML元素的类名:
// 切换主题
function toggleTheme() {
const htmlEl = document.documentElement
if (htmlEl.classList.contains('dark-theme')) {
htmlEl.classList.remove('dark-theme')
uni.setStorageSync('theme', 'light')
} else {
htmlEl.classList.add('dark-theme')
uni.setStorageSync('theme', 'dark')
}
}
// 初始化主题
function initTheme() {
const savedTheme = uni.getStorageSync('theme') || 'light'
if (savedTheme === 'dark') {
document.documentElement.classList.add('dark-theme')
}
}
使用uni-ui主题组件
安装uni-ui主题插件:
npm install @dcloudio/uni-ui
在页面中使用主题组件:
<template>
<uni-theme>
<uni-nav-bar title="标题" />
<uni-card title="卡片标题">卡片内容</uni-card>
</uni-theme>
</template>
适配系统主题
监听系统主题变化:
uni.onThemeChange(function(res) {
if (res.theme === 'dark') {
document.documentElement.classList.add('dark-theme')
} else {
document.documentElement.classList.remove('dark-theme')
}
})
主题相关配置
在pages.json中配置全局样式:
{
"globalStyle": {
"navigationBarTextStyle": "@navigationBarTextStyle",
"navigationBarTitleText": "主题示例",
"backgroundColor": "@backgroundColor",
"backgroundTextStyle": "@backgroundTextStyle"
}
}
创建主题配置文件theme.json:
{
"light": {
"@navigationBarTextStyle": "black",
"@backgroundColor": "#F7F7F7",
"@backgroundTextStyle": "dark"
},
"dark": {
"@navigationBarTextStyle": "white",
"@backgroundColor": "#1A1A1A",
"@backgroundTextStyle": "light"
}
}






