微信小程序镜像胶囊组件(colorui)

    技术2025-04-06  16

    经过数万次的调试,终于镜像出右上角的胶囊!

    示例:

    细节: 1.胶囊距屏幕顶部距离自适应 2.胶囊高度自适应 3.胶囊点击后可像原生组件一样产生反馈(图标变灰) 4.简化wxml代码,只要4行

    下面给出代码:

    capsule.wxml

    <view class="capsule-box" style="top:{{capsuleTop}}px;height:{{capsuleHeight}}px;"> <navigator class='cuIcon-back' open-type="navigateBack"></navigator> <navigator wx:if="{{iconSelect == 'home'}}" class='cuIcon-home' open-type="switchTab" url="/pages/index/index"></navigator> </view>

    capsule.wxss

    @import "/miniprogram_npm/colorui/main.wxss"; @import "/miniprogram_npm/colorui/icon.wxss"; /*-------胶囊按钮-------*/ .capsule-box{ position: fixed; margin-left: 10px; background: rgba(0,0,0,.16); color: #fff; border-radius: 25px; padding: 4px 4px; border: 1rpx solid rgba(255,255,255,0.25); z-index: 99; } .capsule-box navigator{ padding: 8px; font-size: 20px; display: initial; } .capsule-box navigator + navigator{ border-left: 1px solid rgba(255,255,255,0.15); margin: 0 3px; padding: 0 5px; padding-left: 15px; } .navigator-hover { color: gray; background: none; }

    capsule.js

    const app = getApp(); Component({ options: { styleIsolation: 'isolated' }, properties: { iconSelect: { type: String, value: 'home' } }, data: { capsuleTop: app.globalData.capsuleTop, capsuleHeight: app.globalData.capsuleHeight }, })

    app.js

    async onLaunch () { let menuButtonObject = wx.getMenuButtonBoundingClientRect(); // 获取胶囊按钮信息 wx.getSystemInfo({ success: res => { console.log('menuButtonObject', menuButtonObject) console.log('getSystemInfo', res) let statusBarHeight = res.statusBarHeight, // 顶部状态栏高度 capsuleTop = menuButtonObject.top, //胶囊按钮与顶部的距离 navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2;//导航栏的高度(不包括状态栏) this.globalData.navHeight = navHeight; this.globalData.capsuleTop = capsuleTop; this.globalData.capsuleHeight = menuButtonObject.height; // 胶囊按钮高度 this.globalData.windowHeight = res.windowHeight; // 屏幕高度 }, fail(err) { console.log(err); } }) }
    Processed: 0.009, SQL: 9