uniapp自定义导航栏时,根据设备自适应高度

1,777 阅读1分钟

本来是微信开发想监听自定义返回事件,但是onBackPress不适用于微信小程序,所以我们需要自定义导航栏,这个高度吧很不好搞,顶部高度= 状态栏高度+导航栏高度。

下图蓝色区域为状态栏,绿色区域为menu,两块红色+绿色区域为导航栏区域

image.png

image.png

给返回按钮绑定点击事件,点击返回将会弹出toast框,点击确定跳转到上一个页面,取消继续在当前页面


<template>
    <view class="custom_top" :style="{height:totalHeight+'px'}">
         <view :style="{marginTop:contentHeight+'px',marginLeft:20+'rpx'}">
                <img src="/static/img/createStroy/back.svg" @click="toback" class='icon' alt="">
         </view>
    </view>
</template>


<script>
   
  export default {
   data(){
        return {
            // 状态栏高度
            statusBarHeight:0,
            //胶囊的高度
            menu:0,
             //导航栏高度
            navigatorHeight:0,
            // 总高度=状态栏+导航栏高度
            totalHeight:0,
            //返回箭头的位置
            contentHeight:0
        }
   },
    onLoad(){
        let that = this;
        uni.getSystemInfo({
                success(res) {
                    //获取胶囊信息
                    that.menu = uni.getMenuButtonBoundingClientRect()
                    // 获取状态栏的高度
                    that.statusBarHeight = res.statusBarHeight
                    //获取导航栏的高度,导航栏高度= (胶囊-状态栏)*2 + 状态栏高度
                    that.navigatorHeight = (that.menu.top - that.statusBarHeight) * 2 + that.menu.height   //(24-20)*2+32=40
                    that.totalHeight = that.statusBarHeight + that.navigatorHeight //总高度
                    //that.contentHeight = that.menu.top + that.menu.height*0.5 - 20; //24+16
                }
        })
    },
    methods:{
        toback(){
            if(this.model1.stroyInfo.name || this.model1.stroyInfo.intro){
                uni.showModal({
                    title: '提示',
                    content: '当前页面故事内容未保存,您确定要退出吗?',
                    success: function (res) {
                        if (res.confirm) {
                            uni.navigateBack({
                                    delta: 1
                            });
                        }
                    }
                })
            }else{
                uni.navigateBack({
                        delta: 1
                });
            }
  }
}
</script>