
目录一、目的二、解决方案2.1 自定义菜单栏相关代码2.1.1 wxml的实现2.1.2 wxss实现2.1.3相关json和js的实现2.2 问题处理-1、菜单切换后底部菜单栏选择2.3 问题处理-2、页面高度和自定义菜单栏高度适配三、文章总结一、目的最近跟小伙伴一起开发一款微信小程序UI样式这边找的专业设计师朋友设计的效果底部菜单栏这块做了异型的UI效果显示所以需要用到自定义的菜单栏。以前是简单了解过官网也有相关参考示例但是用的过程中发现官网示例并没办法解决所有问题。本次文章主要说明的两个问题1、菜单切换后底部菜单栏选择。2、页面高度和自定义菜单栏高度适配。先放一下完成后的效果图二、解决方案2.1 自定义菜单栏相关代码这里先贴一下实现的相关代码感兴趣的朋友可以看一下。同时也可以看一下微信官方的示例以下是官方示例链接以及自定义tarbar的文件结构https://developers.weixin.qq.com/miniprogram/dev/framework/ability/custom-tabbar.htmlhttps://developers.weixin.qq.com/miniprogram/dev/framework/ability/custom-tabbar.htmlps:首先需要把app.json中的自定义配置启动。2.1.1 wxml的实现view classtab-bar view classtab-bar-border/view view wx:for{{list}} wx:keyindex classtab-bar-item {{index centerIndex ? tab-bar-item-center : }}>2.1.2 wxss实现.tab-bar { position: fixed; bottom: 0; left: 0; right: 0; height: 135rpx; background: #ffffff; display: flex; padding-bottom: env(safe-area-inset-bottom); } .tab-bar-border { background-color: rgba(0, 0, 0, 0.08); position: absolute; left: 0; top: 0; width: 100%; height: 1px; transform: scaleY(0.5); } .tab-bar-item { flex: 1; text-align: center; display: flex; justify-content: center; align-items: center; flex-direction: column; } .tab-bar-item image { width: 24px; height: 24px; } .tab-bar-item view { font-size: 10px; } .tab-bar-item-center { padding-top: 0; transform: translateY(-10px); } .center-circle { width: 54px; height: 54px; border-radius: 24px; background: linear-gradient(180deg, #E8F5E9 0%, #CDECD4 100%); display: flex; justify-content: center; align-items: center; box-shadow: 0 10px 16px rgba(76, 175, 80, 0.18), 0 0 0 6px rgba(76, 175, 80, 0.08); } .center-circle.active { background: linear-gradient(180deg, #DDF3E3 0%, #BEE7C5 100%); border: 2px solid #4CAF50; transform: translateY(-2px) scale(1.06); } .tab-bar-item-center image { width: 30px; height: 30px; } .tab-bar-item-center view { font-weight: 600; }2.1.3相关json和js的实现json文件比较简短这里就不贴代码了这里的selected无作用因为切换页面后又重新加载了菜单组件需要页面加载完后进行设置。Component({ data: { selected: 0, color: #999999, selectedColor: #4CAF50, centerIndex: 2, list: [填写自己项目中app.json中的菜单list即可。注意相关资源的路径即可] }, methods: { switchTab(e) { const data e.currentTarget.dataset; const url data.path; this.setData({ selected: data.index }) wx.switchTab({ url }) } } })2.2 问题处理-1、菜单切换后底部菜单栏选择最开始想着直接组件的attach事件里面但是无法获取到当前加载的小程序页面来判断哪个选中最后是在每个主页中show方法调用一个通用的切换方法。//页面调用方法 //切换选中样式以下的页面索引根据自己菜单在list中的顺序自行调整 util.SwitchTabbar(1, this); //以下四util.js中的方法 //设置菜单项的样式 const SwitchTabbar (pindex, that) { if (typeof that.getTabBar function that.getTabBar()) { //console.log(菜单切换,pindex); that.getTabBar().setData({ selected: pindex }) } };2.3 问题处理-2、页面高度和自定义菜单栏高度适配这个问题最坑一开始试了好多种方法csdn上也看了相关博客有通过js获取系统高度进行动态配置的或则直接调整页面中的view。如以下方法。没作用。当然这些也不是完全没作用还是可以给一个借鉴一下。同时问题根源是调整除了改变page里内容距离底部的高度首先需要更改page自身高度。同时使用css就可以方便搞定。代码如下page,.container { height: calc(100vh - 135rpx - env(safe-area-inset-bottom)) !important; overflow-y: scroll; }三、文章总结本文解决的问题不算特别复杂但是解决也花了些时间。在搜索的过程中通过AI以及相关博客给出的解决方案并不精准所以这里就记录一下解决过程。