微信小程序,仿微信,下拉显示小程序效果,非常丝滑

在这里插入图片描述

1. 视图层

使用到了微信小程序的movable-view(可移动的视图容器)和movable-view的可移动区域。

微信小程序文档

<!--wxml-->
<view style="position: relative;" class="page-container">
  <view>
    二楼内容
  </view>
  <movable-area class="area-style">
    <movable-view disabled="{
    
    {disabled}}" bindchange="changeMove" bindtouchend="touchend" bindtouchstart="touchstart" y="{
    
    {y}}" class="view-style br" direction="vertical">
      一楼内容
    </movable-view>
  </movable-area>
</view>

3. css

注意:移动区域一定要大于可移动视图容器,否则将无法移动
我这里 .area-style设置200vh .view-style设置100vh
这里有个细节:
当移动区域到最下方时,继续往下滑动,移动区域将会回弹到顶部,
解决方法:
1.设置:移动区域高度 = 可移动区域高度 + 可移动返回高度,
2.通过js控制:在最低点下滑无效即可

/* wxss */
.page-container{
    
    
  height: 100vh;
  overflow: hidden;
  background-color: #aaa;
  text-align: center;
  font-size: 24px;
  font-weight: 500;
  padding-top: 20px;
}
.area-style {
    
    
  height: 200vh;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
}

.view-style {
    
    
  width: 100%;
  height: 100vh;
  background-color: #fafafa;
  text-align: center;
  font-size: 24px;
  font-weight: 500;
  padding-top: 20px;
}

5. js

通过js控制y值,进而实现下滑和上划动画打开/关闭效果。

注意:如果在一楼或者二楼使用到了scroll-view,那么需要在y=minY 或y=maxY的时候,动态控制scroll-view是否可滑动即可。

// ts
Page({
    
    

  /**
   * 页面的初始数据
   */
  data: {
    
    
    y: 0, // 一楼(可滑动块)距离顶部的距离
    minY: 0, // 一楼(可滑动块)距离顶部的最小距离
    maxY: 0,// 一楼(可滑动块)距离顶部的最大距离
    endY: 0,// 滑动结束是y的值
    startY: 0, // 滑动开始时y的值(要么等于minY,要么等于maxY)
    threshold: 100, // 滑动阀值(指 滑动超过此值一段距离,才会打开或者关闭,否则弹回原来的状态)
    disabled: false, // 是否禁止滑动
  },
  // 滑动过程中,把每次滑动的当前值,赋值给endY
  changeMove(e: any) {
    
    
    this.setData({
    
    
      endY: e.detail.y
    })
  },
  // 滑动结束
  touchend() {
    
    
    const {
    
     startY, endY, maxY, minY, threshold } = this.data
    let value;
    // 判断向下滑动
    if (endY > startY && endY - startY > threshold) {
    
    
      // 触发下滑,页面打开二楼
      value = maxY
      // 触发下滑成功,设置震动反馈
      wx.vibrateShort({
    
     type: 'heavy' })
    } else {
    
    
      // 未触发下滑,页面回弹到一楼
      value = minY
    }
    // 判断上划
    if (startY > endY && startY - endY < threshold) {
    
    
      // 触发上滑,页面回到一楼
      value = maxY
    }
    this.setData({
    
    
      y: value
    })
  },
  // 滑动开始
  touchstart() {
    
    
    this.setData({
    
    
      startY: this.data.y
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad() {
    
    
    // 获取屏幕高度
    const res = await wx.getSystemInfo()
    // 设置最大顶部距离(-200,目的是让一楼漏出头,方便上划,或者点击)
    this.setData({
    
    
      maxY: res.screenHeight - 200
    })
  },
})

持续优化,欢迎一起讨论。

猜你喜欢

转载自blog.csdn.net/qq_45142260/article/details/131954258