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

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

1. 设置支持的主题色

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

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选中文字设置成指定主题颜色,如果有其他需求,可自行添加。

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文件

const { applyTheme } = require('../../utils/themeMixin.js')
Page({

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

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

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

<view style="color:{{theme.text}}">

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

5. 动态切换主题颜色

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

Page({

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

    switchTheme(){
        // 这里的black是模拟赋值,通过选择框等方式让用户动态选择
        const theme = "black"; 
        getApp().setTheme(theme);
        applyTheme(this);
    }
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

二饭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值