小程序自定义头部navigationBar

自定义头部高度的计算思路

在这里插入图片描述

先来原生小程序的

首先在app.js文件内的onLanch获取到当前机型的信号区和胶囊区的高度并存入globalData

App({
  onLaunch() {
    this.globalData.info = wx.getSystemInfoSync().statusBarHeight
    this.globalData.top = wx.getMenuButtonBoundingClientRect().top
    this.globalData.bottom = wx.getMenuButtonBoundingClientRect().bottom
  },
  globalData: {
    info:0,
    top:0,
    bottom:0,
  }
})

然后在需要自定义头部的组件内配置"navigationStyle": "custom"

{
  "usingComponents": {},
  "component": true,
  "navigationStyle": "custom"
}

在组件的attached生命周期中获取到globalData里边的状态区以及胶囊区的高度并进行计算
因为我们在使用中需要空出状态栏 所以将状态栏的高度一并传过来设置为padding-top内边距
并使用this.setData()更新data中的heighttop


      attached: function () {
          let obj = getApp().globalData
          let num = obj.bottom + ((obj.top - obj.info))
          let info = obj.info
          this.setData({
              height:num,
              info:info
          })
       },

并使用插值语法为自定义头部设置高度并使用padding-top腾出状态栏的距离

<view class="top" style="height:{{height}}px;padding-top:{{info}}px;">
    <input type="text" placeholder="请输入搜索内容"/>
</view>

接下来是uni-app

计算方式同微信小程序
首先在app.vue中获取我们需要的高度

<script>
	export default {
		onLaunch: function() {
			this.globalData.bottom = uni.getMenuButtonBoundingClientRect().bottom
			this.globalData.top = uni.getMenuButtonBoundingClientRect().top
			this.globalData.info = uni.getSystemInfoSync().statusBarHeight
		},
		onShow: function() {},
		onHide: function() {},
		globalData: {
			top: 0,
			bottom: 0,
			info: 0
		}
	}
</script>

pages.json文件中给需要自定义头部的组件添加"navigationStyle":"custom"字段
组件代码如下

<template>
	<view class="search" :style="'height:'+height+'px;padding-top:'+info+'px;'">
		我是自定义头部
	</view>
</template>
<script>
	export default {
		name: "mysearch",
		data() {
			return {
			height:0,
			info:0
			};
		},
		created() {
			let obj = getApp().globalData
			this.height = obj.bottom + (obj.top - obj.info)
			this.info = obj.info
		}
	}
</script>
<style lang="scss">
.search{
	background-color: #f00;
	color: white;
}
</style>

效果图如下

在这里插入图片描述

结束

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值