uniapp 自定义导航栏适配高度
时间: 2023-06-21 18:17:16 浏览: 218
小程序实现自定义导航栏适配完美版
要在 UniApp 中自定义导航栏并适配高度,你可以按照以下步骤操作:
1. 在 App.vue 文件中,添加一个自定义导航栏组件,如下所示:
```html
<template>
<div>
<custom-nav-bar></custom-nav-bar>
<router-view></router-view>
</div>
</template>
<script>
import CustomNavBar from '@/components/CustomNavBar.vue'
export default {
components: {
CustomNavBar
}
}
</script>
```
2. 在 CustomNavBar.vue 组件中,设置导航栏的样式,并使用 `uni.getSystemInfoSync()` 方法获取系统信息,以动态计算导航栏的高度,如下所示:
```html
<template>
<div class="custom-nav-bar" :style="{ height: navBarHeight + 'px' }">
<div class="custom-nav-bar__left" @click="onLeftClick">
<slot name="left"></slot>
</div>
<div class="custom-nav-bar__title">
<slot></slot>
</div>
<div class="custom-nav-bar__right">
<slot name="right"></slot>
</div>
</div>
</template>
<script>
export default {
computed: {
navBarHeight() {
const systemInfo = uni.getSystemInfoSync()
const statusBarHeight = systemInfo.statusBarHeight || 0
const navigationBarHeight = 44
const totalHeight = statusBarHeight + navigationBarHeight
return totalHeight
}
},
methods: {
onLeftClick() {
uni.navigateBack()
}
}
}
</script>
<style lang="scss">
.custom-nav-bar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 16px;
background-color: #ffffff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
.custom-nav-bar__left {
font-size: 16px;
color: #333333;
}
.custom-nav-bar__title {
font-size: 18px;
font-weight: 500;
color: #333333;
}
.custom-nav-bar__right {
font-size: 16px;
color: #333333;
}
}
</style>
```
3. 在需要使用自定义导航栏的页面中,使用 `uni.getMenuButtonBoundingClientRect()` 方法获取右侧菜单按钮的位置信息,并根据此信息调整页面的样式,使页面内容不被导航栏遮挡,如下所示:
```html
<template>
<div class="page">
<custom-nav-bar>
<template #left>
<uni-icons type="back" size="28" color="#333333"></uni-icons>
</template>
<span>页面标题</span>
<template #right>
<uni-icons type="ellipsis" size="28" color="#333333"></uni-icons>
</template>
</custom-nav-bar>
<div class="content">
页面内容
</div>
</div>
</template>
<script>
export default {
mounted() {
const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
uni.getSystemInfo({
success: (res) => {
const statusBarHeight = res.statusBarHeight || 0
const navBarHeight = this.$refs.navBar.clientHeight
const titleBarHeight = statusBarHeight + navBarHeight
const contentHeight = res.windowHeight - titleBarHeight - menuButtonInfo.height - (menuButtonInfo.top - statusBarHeight) * 2
this.$refs.content.style.height = contentHeight + 'px'
}
})
}
}
</script>
<style lang="scss">
.page {
height: 100%;
.content {
background-color: #f5f5f5;
padding: 16px;
overflow-y: scroll;
}
}
</style>
```
这样,你就可以自定义导航栏并适配高度了。
阅读全文