美文网首页
uniapp实现自定义导航栏随页面滚动展示隐藏

uniapp实现自定义导航栏随页面滚动展示隐藏

作者: 迷失的信徒 | 来源:发表于2023-06-05 16:37 被阅读0次

1、实现原理

通过页面滚动高度计算顶部自定义导航的透明度,当页面向上滑时透明度值变大,反之变小

2、实现

2.1、配置pages.json

先在pages.json中配置navigationStyle

"style": {
        "navigationStyle": "custom"
     }

完整代码

        data() {
            return {
                statusBarHeight: 0,
                op: 0,
            }
        },
        onLoad() {
            uni.getSystemInfo({
                success: (res) => {
                    this.statusBarHeight = res.statusBarHeight
                }
            })
        },

 onPageScroll (res) {
  // res.scrollTop 为页面滚动距离
  let top = res.scrollTop
  // height为状态栏高度+自定义导航栏标题内容高度(这里是44px)
  let height = this.statusBarHeight + 44
  // 判断滚动高度
  // 如果小于顶部自定义导航的高度
  if (top <= height) {
    // 透明度(op) = 滚动距离/导航栏高度
    //  (不做操作 直接计算 this.op = top/height 也可以实现)
    // 由于(滚动距离/导航栏高度)得到0-1之间小数点后n位小数
    // 四舍五入后得到的只能是0/1
    // 因此做如下操作
    this.op = Math.round(top/height*100)/100
  } else {
    // 如果滚动距离大于导航高度,则透明度值为1(不透明)
    this.op = 1
  }
}

<view class="nav" :style="'background-color: rgba(255, 255, 255,' + op +')'">
            <view class="status-bar" :style="'height:' + statusBarHeight + 'px'"></view>
            <view class="title" :style="'color: rgba(0, 0, 0,' + op +')'">
                行程安排
            </view>
        </view>

css

.nav {
            position: fixed;
            top: 0rpx;
            left: 0;
            right: 0;
            background: #fff;

            .title {
                height: 88rpx;
                line-height: 88rpx;
                text-align: center;
            }
        }

相关文章

网友评论

      本文标题:uniapp实现自定义导航栏随页面滚动展示隐藏

      本文链接:https://www.haomeiwen.com/subject/ytcwedtx.html