微信小程序动态切换窗口主题色

在微信开发者工具中动态切换主题颜色会感觉切换页面时有主题颜色闪烁问题,但在真机调试中没有闪烁问题。

1. 设置支持的主题色

在app.js中添加以下内容:

javascript 复制代码
App({
    /* 省略其它无关代码 */
  
    onLaunch() {
        // 从缓存读取主题色
        const theme = wx.getStorageSync('theme') || this.globalData.theme;
        if (theme) {
            this.globalData.theme = theme
            this.setTheme(theme)
        }
    },
  
    /**
     * 设置主题色
     * @param theme
     */
    setTheme(theme) {
        // 动态更新CSS变量
        wx.setStorageSync('theme', theme)
        this.globalData.theme = theme

        const page = getCurrentPages()[getCurrentPages().length - 1]
        page.setData({theme: this.globalData.themeColors[theme]});
    },

    globalData: {
        theme: 'black', // 默认主题
        themeColors: {
            pink: {
                name:'粉色',
                value: 'pink',
                primary: '#1890ff',
                background: '#ffffff', // 仅支持黑白两色
                text: '#ff55a0'
            },
            black: {
                name:'黑色',
                value: 'black',
                primary: '#E6E7E9',
                background: '#ffffff',
                text: '#000000'
            }
        }
    },
})

2. 创建themeMixin.js文件

建议放到utils目录下:如下代码中会将小程序的窗口颜色、窗口标题、TabBar选中文字设置成指定主题颜色,如果有其他需求,可自行添加。

javascript 复制代码
function applyTheme(pageInstance) {
    const app = getApp()
    const theme = app.globalData.theme
    wx.setNavigationBarColor({
        frontColor: app.globalData.themeColors[theme].background,
        backgroundColor: app.globalData.themeColors[theme].text
    })
    wx.setTabBarStyle({
        selectedColor: app.globalData.themeColors[theme].text
    })
    pageInstance.setData({
        theme: app.globalData.themeColors[theme]
    })
}

module.exports = {
    applyTheme
}

3. 页面js中初始化主题样式

下面是某页面的JS文件

javascript 复制代码
const { applyTheme } = require('../../utils/themeMixin.js')
Page({

    /* 省略其它无关代码 */
  
    onLoad(options) {
      this.applyTheme();
    },
})

4. 页面wxml中应用主题颜色

这里只示例了字体颜色,背景颜色相同道理。

javascript 复制代码
<view style="color:{{theme.text}}">

    /* 省略其它无关代码 */
  
</view>

5. 动态切换主题颜色

javascript 复制代码
// 当前是动态切换主题的页面js省略版本
const {applyTheme} = require('../../utils/themeMixin.js')

Page({

    /* 省略其它无关代码 */

    switchTheme(){
        // 这里的black是模拟赋值,通过选择框等方式让用户动态选择
        const theme = "black"; 
        getApp().setTheme(theme);
        applyTheme(this);
    }
})
相关推荐
笨笨狗吞噬者1 小时前
小程序包体积分析利器 -- vite-plugin-component-insight
前端·微信小程序·uni-app
杰建云1673 小时前
小程序转化率低的核心原因是什么?
小程序·小程序制作
中国胖子风清扬4 小时前
基于GPUI框架构建现代化待办事项应用:从架构设计到业务落地
java·spring boot·macos·小程序·rust·uni-app·web app
Greg_Zhong4 小时前
微信小程序中使用canvas中绘制的页面,切换字体的几种实践方式
微信小程序·腾讯云cos·canvas页面切换字体
weikecms5 小时前
外卖CPS小程序哪家系统比较完善
小程序
绝世唐门三哥1 天前
uniapp系列-uniappp都有哪些生命周期?
vue.js·小程序·uniapp
人还是要有梦想的1 天前
如何开发小程序介绍
小程序·notepad++
roamingcode1 天前
支付宝小程序数据可视化避坑指南:@antv/f2 踩坑与最佳实践
信息可视化·小程序·canvas·antv
2501_915921431 天前
HTTP和HTTPS协议全面解析:技术原理与安全应用
安全·http·ios·小程序·https·uni-app·iphone
double_eggm2 天前
微信小程序2
微信小程序·小程序