微信小程序实现侧滑效果(类似QQ侧滑界面)

 效果浏览

代码实现

wxml

<view class="outBox" bindtouchstart="out_touchStart" bindtouchmove="out_touchMove" bindtouchend="out_touchEnd">
  <text style="width: 100vw;text-align: center;">主界面</text>
  <view class="sliderPage" style="transform:translateX({
   
   {moveX}});">
    <text>侧滑界面</text>
  </view>
</view>

wxss

.outBox {
  height: 100vh;
  width: 100vw;
  background: rgba(255, 255, 255, 0.466);
  display: flex;
  align-items: center;
}

.sliderPage {c
  position: fixed;
  height: 100vh;
  width: 80vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.842);
  box-shadow: 2px 0px 10px 0px #00000038;
  transform: translateX(-80vw);
  transition: 0.2s;
}

ts

Page({

  /**
   * 页面的初始数据
   */
  data: {
    fullWidth: 0,
    vw: 0,
    moveX: '-80vw',
    startX: 0,
    sliderActive: false,
    watchMoveX: 0,
  },

  out_touchStart(e: any) {
    let { touches } = e
    this.setData({ startX: touches[0].clientX })
  },

  out_touchMove(e: any) {
    let { touches } = e
    let nowX = touches[0].clientX
    let moveX = nowX - this.data.startX

    if (this.data.sliderActive) {
      if (moveX >= 0 || moveX < -(this.data.fullWidth * 0.8)) return
      this.setData({
        moveX: `${moveX}px`,
        watchMoveX: moveX
      })
    } else {
      if (moveX <= 0 || moveX > (this.data.fullWidth * 0.8)) return
      this.setData({
        moveX: `${-80 * this.data.vw + moveX}px`,
        watchMoveX: moveX
      })
    }
  },

  out_touchEnd(e: any) {
    if (!this.data.sliderActive) {
      if (this.data.watchMoveX > (this.data.fullWidth / 4)) {
        this.setData({
          moveX: `${0}vw`,
          sliderActive: true,
          watchMoveX: 0
        })
      } else this.setData({ moveX: `${-80}vw` })
    } else {
      if (this.data.watchMoveX < -(this.data.fullWidth / 4)) {
        this.setData({
          moveX: `${-80}vw`,
          sliderActive: false,
          watchMoveX: 0
        })
      } else this.setData({ moveX: '0vw' })
    }
  },

  // ------------------------------

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    wx.createSelectorQuery().select(".outBox").boundingClientRect().exec(res => {
      this.setData({
        vw: res[0].width / 100,
        fullWidth: res[0].width
      })
    })
  },
  ....//省略其他周期函数
})

注意

  1. 实现这种侧滑效果的方法有很多,这只是其中一种
  2. 两个界面是嵌套关系,因此可以只通过外部元素节点,也就是主界面的touch控制来实现滑动效果

猜你喜欢

转载自blog.csdn.net/Ice1774/article/details/130208175