小程序换肤
1、需求:接手一个别人做的小程序,需要加上换肤的功能,看了网上几款换肤实现的思路,很麻烦了,工作量又大,于是自己想出这个比较好的解决方案
2、思路:利用css的属性选择器来设置不同的自定义变量,利用globalData和Behavior去实时获取主题并设置页面属性,然后在页面使用已经定义好的自定义变量就好了
3、具体实施:
3-1、设置主题
新建一个theme.wxss
[data-theme=theme1]{ --text:blue; --bg:aqua; } [data-theme=theme2]{ --text:red; --bg:pink; }
在app.wxss引入
@import "style/theme.wxss";
在页面wxml处最外层加上data-theme属性(theme和themeSwitch会在3-2里说明)
<view class="page" data-theme="{{theme}}"> <text>小程序换肤小程序换肤小程序换肤小程序换肤小程序换肤小程序换肤小程序换肤</text> <button bindtap="themeSwitch">按钮</button> </view>
页面wxss里使用自定义变量(到了这一步并不能看到效果,因为属性还没设置上去)
.page{ width: 100vw; height: 100vh; background-color: var(--bg); } text{ color: var(--text); }
3-2、切换主题
在app.js的globalData里新增theme变量,并在app.js引入一个名为theme的Behavior实例
// app.js
const theme=require('utils/theme.js')
App({ onLaunch: function () {
this.globalData.theme=wx.getStorageSync('theme') || 'theme1'
if (wx.getStorageSync('theme') == 'theme1') {
wx.setNavigationBarColor({
frontColor: "#ffffff",
backgroundColor: "#EB2D27",
})
} else if (wx.getStorageSync('theme') == 'theme2') {
wx.setNavigationBarColor({
frontColor: "#ffffff",
backgroundColor: "#0000FF",
})
}
}, globalData: { theme: 'theme1' }, theme });
theme.js设置的Behavior实例
module.exports = Behavior({ data: { theme: '' }, ready: function () { this.setData({ theme: getApp().globalData.theme }) this.setTheme() }, methods: { themeSwitch: function () { if (this.data.theme == 'theme1') { this.setData({ theme: "theme2" }) wx.setStorageSync('theme', 'theme2') getApp().globalData.theme = "theme2" this.setTheme() } else if (this.data.theme == 'theme2') { this.setData({ theme: "theme1" }) wx.setStorageSync('theme', 'theme1') getApp().globalData.theme = "theme1" this.setTheme() } }, setTheme: function () { if (this.data.theme == 'theme1') { wx.setNavigationBarColor({ frontColor: "#ffffff", backgroundColor: "#EB2D27", }) } else if (this.data.theme == 'theme2') { wx.setNavigationBarColor({ frontColor: "#ffffff", backgroundColor: "#0000FF", }) } } } })
在页面加上behaviors: [app.theme]就大功告成
const app=getApp() Page({ behaviors: [app.theme], /** * 页面的初始数据 */ data: { }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { }, })
4、效果(要修改顶部之类也可以在app.theme里添加)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」