当前位置:   article > 正文

微信小程序监听手机系统自带的左右滑动返回事件_小程序监听返回事件

小程序监听返回事件

微信小程序返回的时候想直接返回首页,但是左滑是上一页,和navigateBack一样,所以就监听了一下,后来一想在页面卸载的时候也可以,还可以使用getCurrentPages()方法,拿到是一个数组,官方文档

<view class="container" bindtouchmove="handleTouchMove">
  <!-- 页面内容 -->
</view>
  • 1
  • 2
  • 3
Page({
  data: {
    startX: 0, // 记录触摸开始时的X坐标
    endX: 0,  // 记录触摸结束时的X坐标
  },

  handleTouchMove: function(e) {
    if (e.touches.length == 1) {
      // 单指触摸,记录坐标
      var touch = e.touches[0];
      this.setData({
        endX: touch.clientX,
      });

      // 判断是否滑动到足够距离(例如10px),并且判断是左滑还是右滑
      if (Math.abs(this.data.endX - this.data.startX) > 10) {
        if (this.data.endX < this.data.startX) {
          console.log('右滑');
        } else {
          console.log('左滑');
        }
        // 重置起始坐标,以便进行下一次判断
        this.setData({
          startX: this.data.endX,
          endX: 0,
        });
      }
    }
  },

  // 你可以在这里添加触摸开始的事件处理,以记录起始坐标
  handleTouchStart: function(e) {
    if (e.touches.length == 1) {
      var touch = e.touches[0];
      this.setData({
        startX: touch.clientX,
        endX: 0,
      });
    }
  },

  // ... 其他页面逻辑
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

需要添加更多的逻辑来处理边界情况(如多点触摸、滑动距离的判断阈值等)。同时,由于触摸事件的频繁触发,可能还需要考虑性能优化和防抖/节流等技术。大致监听然后返回首页的。有好的建议可以留言。
还有一种办法就是直接在卸载页面onunload里面直接写跳转页面的方法.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/964195
推荐阅读
相关标签
  

闽ICP备14008679号