微信小程序自定义顶部导航栏,使背景图置顶;当向上滚动页面时,实现顶部导航颜色渐变
效果图
实现方法
一、在pages.json中设置"navigationStyle": “custom”
代码如下(示例):
"path": "pages/home/home",
"style": {
"navigationBarTitleText": "XX网络科技",
"navigationBarBackgroundColor": "#309AEC",
"navigationBarTextStyle": "white",
"enablePullDownRefresh": false,
"backgroundColor": "#ffffff",
"navigationStyle": "custom"
}
二、在页面中配置
提示:由于不同的手机机型顶部导航高度不一样,所有要获取手机的信息
实现方法
总共三步:
1、初始化获取顶部导航信息
2、顶部导航文字上方通过view占位,同时设置顶部导航字体高和行高与胶囊保持一致,实现顶部导航文字在不同机型居中对齐
3、监听滚动事件,不滚动时不加颜色,滚动时给顶部加动态样式
代码如下(示例):
<template>
<view class="Box">
<!-- 设置背景图片及自适应高度 -->
<view class="contain-box" :style="[{backgroundImage:'url('+backgroundImg+')'}, 'height:'+s_topImg+'rpx']" v-for="(item,index) in swipers" :key="index">
<!-- 滚动动态设置样式 -->
<view :class="scrollTopShow?'top-item1':'top-item2'":style="'background:rgba(48, 154, 236,' +topOpacity+')'">
<!-- 胶囊以上占位盒子 -->
<view :style="'height:'+s_top+'rpx', 'line-height:'+s_top+'rpx'"></view>
<!-- 动态设置高和行高与胶囊保持一致 -->
<view class="title-type" :style="['height:'+s_height+'rpx','line-height:'+s_height+'rpx']">
XX网络科技
</view>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
backgroundImg: '', // 顶部背景图
s_top: '', //胶囊距离顶部距离
s_height: '', //胶囊行高
s_topImg: '',
scrollTopShow: true, // 顶部颜色默认隐藏
topOpacity: 0,
}
},
created() {
this.initTopImg();
},
// 监听滚动事件
onPageScroll(e) { //nvue暂不支持滚动监听,可用bindingx代替
let scrollTop = e.scrollTop;
this.topOpacity = scrollTop / 300 > 0.9 ? 1 : scrollTop / 300
if (e.scrollTop != 0) {
this.scrollTopShow = false;
} else {
this.scrollTopShow = true;
}
},
methods: {
// 初始化顶部背景图
initTopImg() {
let menuButtonInfo = uni.getMenuButtonBoundingClientRect();
this.s_top = menuButtonInfo.top * 2;
this.s_topImg = menuButtonInfo.top * 2 + 508;
this.s_height = menuButtonInfo.height * 2;
},
}
}
</script>
<style lang="scss" scoped>
.contain-box {
width: 100%;
background-size: 100% 100%;
align-items: center;
.top-item1 {
.title-type {
font-size: 36rpx;
font-weight: 400;
color: #fff;
display: flex;
justify-content: center;
/* 水平居中 */
}
}
.top-item2 {
position: fixed;
top: 0;
width: 100%;
.title-type {
font-size: 36rpx;
font-weight: 400;
color: #fff;
display: flex;
justify-content: center;
/* 水平居中 */
}
}
}
</style>