当前位置: 首页 > news >正文

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

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

1. 设置支持的主题色

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

App({/* 省略其它无关代码 */onLaunch() {// 从缓存读取主题色const theme = wx.getStorageSync('theme') || this.globalData.theme;if (theme) {this.globalData.theme = themethis.setTheme(theme)}},/*** 设置主题色* @param theme*/setTheme(theme) {// 动态更新CSS变量wx.setStorageSync('theme', theme)this.globalData.theme = themeconst 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.themewx.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);}
})
http://www.dtcms.com/a/298473.html

相关文章:

  • 多智能体强化学习入门:从基础到 IPPO 算法—强化学习(20)
  • 2507C++,C++协程的发送者
  • 浅谈生成式AI语言模型的现状与展望
  • haproxy七层代理(原理)
  • SawtoothSoftware 模板注入漏洞复现(CVE-2025-34300)
  • 8.异常处理:优雅地处理错误
  • ISIS高级特性GR
  • Springboot+activiti启动时报错XMLException: Error reading XML
  • 优思学院|QC七大手法之一的检查表应如何有效使用?
  • 【unitrix】 6.15 “非零非负一“的整数类型(NonZeroNonMinusOne)特质(non_zero_non_minus_one.rs)
  • 亚马逊广告策略:如何平衡大词和长尾词的效果?
  • 倩女幽魂手游代言人杨洋携剑仙入世 仙姿临世锋芒毕露
  • docker-compose:未找到命令的检查步骤和修复
  • ABP VNext + OData:实现可查询的 REST API
  • 服务端处于 TIME_WAIT 状态的 TCP 连接,收到相同四元组的 SYN 后会发生什么?详解
  • HCIP上HCIA复习静态综合实验
  • 移动端设备能部署的llm
  • 系统日志与用户信息绑定实现日志跟踪
  • 前端基础知识Vue系列 - 27(Vue项目中如何解决跨域)
  • 从 SQL Server 到 KingbaseES V9R4C12,一次“无痛”迁移与深度兼容体验实录
  • js基础概念-1
  • 牛客NC16660 [NOIP2004]FBI树(递归 + 二叉树后序遍历)
  • electron中IPC 渲染进程与主进程通信方法解析
  • 常用设计模式系列(十二)—享元模式
  • 如何在 FastAPI 中玩转 GraphQL 和 WebSocket 的实时数据推送魔法?
  • C++中使用Essentia实现STFT/ISTFT
  • git 连接GitHub仓库
  • 强化学习之策略熵坍塌优化-clip conv kv conv
  • 若依搭建详解
  • Android Paging 分页加载库详解与实践