0
点赞
收藏
分享

微信扫一扫

小程序自定义头部navigationsBar

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

在这里插入图片描述

先来原生小程序的

首先在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 top = obj.top
          this.setData({
              height:num,
              top:top
          })
       },

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

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

效果图如下

在这里插入图片描述

结束

举报

相关推荐

0 条评论