uniapp自定义顶部导航栏

前言

在使用uni-app开发小程序的过程中,经常会有需要自定义顶部导航栏的需求。

1、设置 “navigationStyle”: “custom”

自定义导航栏需要在page.json文件内设置 “navigationStyle”: “custom” 属性,添加后自定义导航栏就生效了。

单页面配置自定义导航栏

如果你所有全页都要自定义导航栏,在 “globalStyle” 中配置 “navigationStyle”: “custom” 属性即可。

2、创建一个自定义导航栏组件

custom-nav-bar.vue

<template>
	<view class="tw-nav-bar">
		<view class="nav-bar">
			<view class="status-bar" :style="{height: getStatusBarHeight() + 'px'}"></view>
			<view class="title-bar" :style="{height: getTitleBarHeight() + 'px', marginLeft: getLeftIcon() + 'px'}">
				<view class="title">{{ title }}</view>
				<navigator class="search" url="/pages/search/search">
					<uni-icons class="icon" type="search" color="#888" size="18"></uni-icons>
					<text class="text">搜索</text>
				</navigator>
			</view>
		</view>

		<view class="fill" :style="{height: getNavBarHeight() + 'px'}"></view>
	</view>
</template>

<script setup>
import { getStatusBarHeight, getTitleBarHeight, getNavBarHeight, getLeftIcon } from '@/utils/system.js';

defineProps({
	title: {
		type: String,
		default: '壁纸'
	}
})
</script>

<style lang="scss" scoped>
.nav-bar {
	width: 100%;
	position: fixed;
	top: 0;
	left: 0;
	z-index: 10;
	background: linear-gradient(to bottom, transparent, #fff 400rpx), linear-gradient(to right, #beecd8, #f4e2d8);
	.status-bar {
		border: 1px solid red;
	}
	.title-bar {
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		.title {
			font-size: 22rpx;
			font-weight: 700;
			color: $text-font-color-1;
		}
		.search {
			width: 220rpx;
			height: 50rpx;
			margin-left: 30rpx;
			background: rgba(255, 255, 255, 0.4);
			border: 1px solid #fff;
			border-radius: 60rpx;
			font-size: 28rpx;
			color: #999;
			display: flex;
			align-items: center;
			.icon {
				margin-left: 15rpx;
			}
			.text {
				padding-left: 10rpx;
			}
		}
	}
}
</style>

获取状态栏、标题栏、整个头部的高度的 system.js

const SYSTEM_INFO = uni.getSystemInfoSync();

// 状态栏高度
export const getStatusBarHeight = () => SYSTEM_INFO.statusBarHeight || 0;

// 标题栏高度
export const getTitleBarHeight = () => {
    if (uni.getMenuButtonBoundingClientRect) {
        const { top, height } = uni.getMenuButtonBoundingClientRect();
        return height + (top - getStatusBarHeight()) * 2;
    } else {
        return 40;
    }
}

// 整个头部高度
export const getNavBarHeight = () => getStatusBarHeight() + getTitleBarHeight();

// 头条小程序左侧logo
export const getLeftIcon = () => {
    // #ifdef MP-MP-TOUTIAO
        const { leftIcon: { left, width }} = tt.getCustomButtonBoundingClientRect();
        return left + parseInt(width);
    // #endif

    // #ifndef MP-MP-TOUTIAO
        return 0;
    // #endif
}

3、在页面中使用自定义导航栏组件

自定义导航栏可以更加灵活多变,根据自己需求进行设置,官方也提供了组件uni-nav-bar自定义导航栏

赞(0) 打赏

评论 抢沙发

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫

微信扫一扫