UniApp多端适配黑科技:动态主题切换与全局样式管理实战
一、动态主题架构设计
基于CSS变量的跨平台主题解决方案:
// theme-manager.js 主题管理模块
const themes = {
light: {
'--primary-color': '#1890ff',
'--text-color': '#333',
'--bg-color': '#fff'
},
dark: {
'--primary-color': '#177ddc',
'--text-color': '#f0f0f0',
'--bg-color': '#1a1a1a'
},
blue: {
'--primary-color': '#1e90ff',
'--text-color': '#333',
'--bg-color': '#f0f8ff'
}
}
export default {
current: 'light',
init() {
const savedTheme = uni.getStorageSync('theme') || 'light'
this.applyTheme(savedTheme)
},
applyTheme(themeName) {
if (!themes[themeName]) return
this.current = themeName
uni.setStorageSync('theme', themeName)
// 动态更新CSS变量
const style = document.documentElement.style
Object.entries(themes[themeName]).forEach(([key, value]) => {
style.setProperty(key, value)
})
// 小程序端特殊处理
#ifdef MP-WEIXIN
wx.setNavigationBarColor({
frontColor: themeName === 'dark' ? '#ffffff' : '#000000',
backgroundColor: themes[themeName]['--primary-color']
})
#endif
}
}
核心优势:实时切换、多端兼容、维护简单、性能高效
二、高级功能实现
1. 组件级主题适配
<template>
<view class="my-component">
<text class="title">标题</text>
<button class="btn">按钮</button>
</view>
</template>
<style lang="scss">
.my-component {
background-color: var(--bg-color);
padding: 20rpx;
.title {
color: var(--text-color);
font-size: 32rpx;
}
.btn {
background-color: var(--primary-color);
color: #fff;
}
}
</style>
2. 平台差异化样式
/* 全局样式文件 */
page {
/* 基础变量定义 */
--primary-color: #1890ff;
--text-color: #333;
/* 小程序特有样式 */
#ifdef MP-WEIXIN
--nav-bar-height: 44px;
--tab-bar-height: 50px;
#endif
/* H5特有样式 */
#ifdef H5
--nav-bar-height: 56px;
--tab-bar-height: 0;
#endif
/* 安卓平台调整 */
#ifdef APP-PLUS && ANDROID
--primary-color: #1e88e5;
#endif
}
/* 动态主题应用 */
.container {
color: var(--text-color);
background: var(--bg-color);
min-height: calc(100vh - var(--nav-bar-height) - var(--tab-bar-height));
}
三、电商应用实战案例
1. 用户自定义主题系统
// 主题编辑器组件
export default {
data() {
return {
customTheme: {
primary: '#1890ff',
text: '#333',
bg: '#fff'
}
}
},
methods: {
updateTheme() {
const theme = {
'--primary-color': this.customTheme.primary,
'--text-color': this.customTheme.text,
'--bg-color': this.customTheme.bg
}
// 保存自定义主题
uni.setStorageSync('customTheme', theme)
// 动态应用
const style = document.documentElement.style
Object.entries(theme).forEach(([key, value]) => {
style.setProperty(key, value)
})
// 同步到云端
this.saveToCloud()
},
saveToCloud() {
uniCloud.callFunction({
name: 'saveUserTheme',
data: {
userId: getApp().globalData.userId,
theme: this.customTheme
}
})
}
}
}
四、多端适配最佳实践
- 性能优化:使用CSS变量替代JS动态修改样式
- 降级方案:为不支持CSS变量的设备提供默认主题
- 调试技巧:使用Chrome检查CSS变量应用情况
- 设计规范:建立主题变量命名规范
- 单元测试:验证各平台主题渲染效果