• 效果

功能演示

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

  • 配置pages.json
    先在pages.json中配置navigationStyle

{
  	"path":"pages/cart/cart",
   	"style": {
     	"navigationStyle": "custom"
   	 }
}
  • 状态栏占位元素
    由于自定义导航栏,顶部状态栏会被页面覆盖,因此需要一个元素来占位
    元素高度计算如下:
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
  }
}

  • 完整代码
<template>
  <view class="">
    <!-- S 自定义导航栏 -->
    <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 +')'">
        XXXX
      </view>
    </view>
    <!-- E 自定义导航栏 -->
    
    <!-- S 页面内容区域 -->
    <view class="content"></view>
    <!-- E 页面内容区域 -->
  </view>
</template> 

<script>
  export default {
    data () {
      return {
        statusBarHeight: 0,
        op: 0
      }
    },
    onLoad () {
      uni.getSystemInfo({
        success: (res) => {
          this.statusBarHeight = res.statusBarHeight
        }
      })
    },
    onPageScroll (res) {
      let top = res.scrollTop
      let height = this.statusBarHeight + 44
      if (top <= height) {
        this.op = Math.round(top/height*100)/100
      } else {
        this.op = 1
      }
    },
  }
</script>

<style>
  .nav {
    position: fixed;
    top: 0rpx;
    left: 0;
    right: 0;
    background: #fff;
  }
  .content {
    height: 150vh;
    background: #f2f2f2;
  }
  .title {
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
  }
</style>


不喜勿喷!!!
不喜勿喷!!!
不喜勿喷!!!
重要的事情说三遍

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐