微信小程序自定义navigationBar与胶囊对齐,解决方案

这篇博客详细介绍了如何在微信小程序中通过获取系统状态栏高度和胶囊信息,动态设置自定义导航栏的高度和位置,从而实现页面顶部的布局优化。内容包括在`index.js`中获取和存储状态栏高度,以及在`index.wxml`和`index.wxss`中应用这些值来创建一个包含搜索框和导航栏的固定顶栏布局。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

index.js

Page({
    data: { 
    	// 状态栏上方空白
        navigationBarTop: wx.getStorageSync('navigationBarTop'),
        // 导航栏高度
        navigationBarHeight: wx.getStorageSync('navigationBarHeight') ,
    onLoad() {
        // 获取状态栏高度
        const {
            statusBarHeight,
        } = wx.getSystemInfoSync()
        //获取胶囊信息
        const {
            top,
            height
        } = wx.getMenuButtonBoundingClientRect()
        // 自定义导航栏的到顶部距离 = 状态栏高度
        wx.setStorageSync('navigationBarTop', statusBarHeight)
        // 自定义导航栏高度 = 胶囊高度 + 胶囊的padding*2。如果获取不到设置为38
        wx.setStorageSync('navigationBarHeight', height ? height+(top - statusBarHeight) * 2 : 38)
    }
 })

index.wxml

<view class="search" style="height: {{navigationBarHeight}}px;padding-top: {{navigationBarTop}}px;">
  <view class="city">北京市<image class="icon" src="/static/icons/下箭头.png"></image></view>
  <view class="input">
  <image class="icon" src="/static/icons/搜索.png"></image>
  <input type="text" placeholder="请输入电影"/>
  </view>
</view>
<!-- 占位 -->
<view style="height: {{navigationBarHeight+navigationBarTop}}px;"></view> 
<view class="navbar">
  <text class="item {{currentTab==index?'active':''}}" wx:for="{{navbar}}" data-tab_index="{{index}}" wx:key="unique" bindtap="changeNavBar">{{item}}</text>
</view>

index.wxss

.search {
  z-index: 10;
  width: 100%;
  display: flex;
  align-items: center;
  padding: 0rpx 20rpx;
  font-size: 26rpx;
  position: fixed;
  background-color: #fff;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值