自定义头部高度的计算思路
先来原生小程序的
首先在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中的height
和top
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>
效果图如下
结束