微信小程序自定义顶部导航,滚动页面顶部导航颜色渐变

微信小程序自定义顶部导航栏,使背景图置顶;当向上滚动页面时,实现顶部导航颜色渐变


效果图

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

实现方法

一、在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>
  • 6
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

smileAgain-lg

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值