wx.getSystemInfoSync(),获取小程序的系统信息,对于开发者来说这个接口的好处就是能够获取到小程序状态栏的高度。
有时候我们不一定使用小程序默认状态栏的样式,重新定义自己喜欢的样式,这时我们需要设置高度。但是在不同设备中小程序的状态栏高度不同,所以我们需要动态的设置状态栏的高度,动态高度这个变量就是通过wx.getSystemInfoSync()函数获取得到的。
首先要自定义一个导航组件:navigation
navigation.js:
const app = getApp()
Component({
properties: {
navbarData: {
//navbarData 由父页面传递的数据,变量名字自命名
type: Object,
value: {},
observer: function (newVal, oldVal) {}
}
},
data: {
height: "",
//默认值 默认显示左上角
navbarData: {
showCapsule: 1
},
imageWidth: wx.getSystemInfoSync().windowWidth, // 背景图片的高度
imageHeight: '', // 背景图片的长度,通过计算获取
},
attached: function () {
// 获取是否是通过分享进入的小程序
this.setData({
share: app.globalData.share
})
// 定义导航栏的高度 方便对齐
wx.getSystemInfo({
success: res => {
console.log(res.statusBarHeight)
this.setData({
height: res.statusBarHeight
})
}
})
},
methods: {
// 计算图片高度
imgLoaded(e) {
console.log(e)
this.setData({
imageHeight: e.detail.height *
(wx.getSystemInfoSync().windowWidth / e.detail.width)
})
}
},
})
navigation.wxml:
<view class='nav-wrap' style="height:{{height*2+44}}px">
<!-- 导航栏背景图片 -->
<image class="backgroundimg" src="http://img4.imgtn.bdimg.com/it/u=25651867,761734299&fm=26&gp=0.jpg" mode="center" bindload="imgLoaded"/>
<!-- // 导航栏 中间的标题 -->
<view class='nav-title' style='line-height: {{height*2 + 44}}px; color:#fff;border:1px solid red;'>
{{navbarData.title}}
</view>
</view>
navigation.wxss:
/* navbar.wxss */
/* 顶部要固定定位 标题要居中 自定义按钮和标题要和右边微信原生的胶囊上下对齐 */
.nav-wrap {
position: fixed;
width: 100%;
top: 0;
background-image: linear-gradient(#2f52bc, #9198e5, #d0d9f4);
color: #000;
z-index: 9999999;
overflow: hidden;
font-size: 20px;
/* height: 200rpx; */
}
/* 背景图 */
.backgroundimg {
position: absolute;
z-index: -1;
width: 100%;
height: 100%;
}
/* 标题要居中 */
.nav-title {
position: absolute;
text-align: center;
/* max-width: 400rpx; */
overflow: hidden;
white-space: nowrap;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
font-size: 36rpx;
color: #2c2b2b;
border: 1px solid red;
}
.nav-capsule {
display: flex;
align-items: center;
margin-left: 30rpx;
width: 140rpx;
justify-content: space-between;
height: 100%;
}
.back-pre {
width: 32rpx;
height: 36rpx;
margin-top: 4rpx;
padding: 10rpx;
}
.nav-capsule {
width: 36rpx;
height: 40rpx;
margin-top: 3rpx;
}
然后在需要自定义导航的页面中引入组件:
在index.json代码
{
"usingComponents": {
"nav-bar": "../Components/navbar/navbar"
},
"navigationStyle": "custom"
}
index.wxml:
<nav-bar navbar-data='{{nvabarData}}'></nav-bar>
文章评论