自定义导航栏渐变色,先上效果

uniapp开发微信小程序自定义顶部导航栏

使用uniapp开发小程序,在不同界面,要去对页面进行修改顶部导航栏。

比如说要去定义导航栏的背景颜色,常规的去定义导航栏背景颜色

全局定义导航栏

"window": {
   "navigationBarBackgroundColor": "#32A2FD",  // 顶部背景颜色
    "navigationBarTitleText": "123456",         // 顶部文字
    "navigationStyle": "default",               // 是否自定义导航栏,当"default"为"custom"时开启自定义头部导航栏选项
    "navigationBarTextStyle": "white",          // 顶部文字颜色 仅支持 white/black    
},

单页面定义导航栏

"path": "pages/cargo/pickUpGoods",//页面路径
"style": {
	"navigationBarTitleText": "uni-app", // 顶部文字
	"navigationBarBackgroundColor": "#fff", // 顶部背景颜色
	"navigationBarTextStyle": "black" // 顶部文字颜色
}

重点来了,导航栏设置渐变色

踩坑,开始我以为把顶部导航栏的颜色换成渐变的就可以了,但是不行

查了之后才知道,设置渐变色要去自定义背景颜色

首先  如果是全部页面就在window里面添加,如果是单页面就在页面添加

"navigationStyle": "custom"

"path": "pages/cargo/shipments",
"style": {
	"navigationBarTitleText": "uni-app",
	"navigationStyle": "custom",//设置自定义导航栏
}

然后,自己封装一个组件,

<template>
	<view class="prohibition">
		<view class="demo" :style="[{background},{color},{height},{paddingTop}]">
			<!-- 左侧返回按钮 -->
			<view class="left" @click="onBack" v-if="back" :style="[{color},{paddingTop}]">
				<uni-icons type="arrowleft" size="30" :color='color'></uni-icons>
				<!-- 此处图标使用的是 uni-ui图标 -->
			</view>
			<!-- 中间标题文字 -->
			<view class="title">
				{{title}}
			</view>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				height: 0, 
				paddingTop: 0,
			}
		},
		// props: ["title", "back"],
		props:{
			title:{ // 标题文字(默认为空)
				type:String,
				default:''
			},
			color:{ // 标题和返回按钮颜色(默认白色)
				type:String,
				default:'#fff'
			},
            //建议使用background  因为使用backgroundColor,会导致不识别渐变颜色
			background:{ // 背景颜色(不传值默认透明)
				type:String,
				default:'transparent'
			},
			back:{ // 是否显示返回按钮(不传值默认不显示)
				type:Boolean,
				default:false
			},
		},
		created() {
			const demo = uni.getMenuButtonBoundingClientRect()
			this.height = demo.height + "px"
			this.paddingTop = demo.top + "px"
		},
		methods: {
			// 左侧返回按钮调用
			onBack() {
				this.$emit("onBack")
			}
		}
	}
</script>
<style lang="less">
	.demo {
		position: relative;//注意,建议使用相对定位,因为固定定位会脱离文档流,然后你还要去设置marginTop值
		// position: fixed;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 26rpx;
		z-index: 100;
		padding-bottom: 10rpx;
		.left {
			float: left;
			position: absolute;
			width: 100rpx;
			height: 50rpx;
			top: 0;
			bottom: 0;
			left: 20rpx;
			color: #fff;
			margin: auto;
		}
		.title {
			font-size: 36rpx;
			font-family: Source Han Sans CN;
			// color: #FFFFFF;
		}
	}
</style>

然后,引入你的这个组件,写在页面的最上面

uniapp开发微信小程序自定义顶部导航栏

 代码在这里

<navbar class="header" :background="backgroundColor" back :title="title" @onBack="goBack"></navbar>

引入组件,使用

uniapp开发微信小程序自定义顶部导航栏

踩了很多坑,制作不易。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。