微信小程序自定义头部学习笔记
首先看一下在不同机型上自定义头部高度效果(黄色部分):
首先给需要自定义头部的页面文件夹下的json(index.json或xx.json)文件添加:
这一步的目的是把自定义的头部去掉,给我们自己写的头部腾出位置。
{
"navigationStyle": "custom" // 将navigationStyle从默认default改为custom
}
in index.wxml:
<view class="custom_header" style="height: {{navH}}px"> //
新头部
</view>
css部分:
.custom_header{
width: 100vw;
background: yellow;
line-height: 180rpx;
text-align: center;
font-weight: bold;
position: fixed;
left: 0;
top: 0;
}
下面就是一步一步进行设置:
in app.js:
App({
globalData: {
navHeight: 0 // 声明一个全局变量用于记录小程序头部的高度
},
onLaunch: function () {
wx.getSystemInfo({
success: res => {
this.globalData.navHeight = res.statusBarHeight + 46; // 赋值导航高度
}, fail(err) {
console.log(err);
}
})
}
})
in index.js:
Page({
data: {
navH: 0, // 声明一个变量
},
onLoad: function(options) {
var that = this;
setTimeout(function () {
that.setData({
navH: app.globalData.navHeight // 给刚刚声明的变量附上全局获取的nav高度
})
wx.hideLoading()
}, 1000)
}
})
in wxml:
<view class='header' style="height: {{navH}}px">
<image src="../../images/nav_back.png"></image>
<text>面试房间</text>
</view>
可以去我的GitHub下载完整code,本地试运行一下:自定义小程序头部
后记
关于app.js文件
App()函数用来注册一个小程序,接受object类型的参数,onLaunch()方法会在打开应用时执行。
关于app.json文件
关于app.json文件:是对整个小程序的全局配置,在这个文件中配置小程序是由哪些页面组成,窗口颜色,导航条样式,默认标题等。app.json中不可以加注释,否则会报错。示例如下:
{
"pages": [
"pages/index/index",
"pages/logs/logs"
],
"window": {
“backgroundColor”: "#fff",
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "red",
"navigationBarTitleText": "我的小程序",
"enablePullDownRefresh": true
}
}