小程序监听屏幕滑动事件

时间:2022-07-28
本文章向大家介绍小程序监听屏幕滑动事件,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

小程序监听屏幕滑动事件

功能设计背景

  1. 小程序页面点击事件的坐标系是以左下角为原点的直角坐标系。
  2. 微信小程序提供bindtouchstartbindtouchend接口用于监听触点的变化。

功能实现

1.在你需要监听的块外增加监听遮罩层,包含待监听块在内

<view  bindtouchstart="touchStart" bindtouchend="touchEnd">
	<!--待监听功能模块-->
</view>

2.根据触点的起始位置和终止位置计算滑动方向(在data中配置touchxtouchy数值)

    touchStart(e) {
      console.log(e)
      var that = this;
      that.setData({
        touchx: e.changedTouches[0].clientX,
        touchy: e.changedTouches[0].clientY
      })
    },
    touchEnd(e) {
      console.log(e)
      var that = this;
      let x = e.changedTouches[0].clientX;
      let y = e.changedTouches[0].clientY;
      let turn = "";
      if (x - that.data.touchx > 50 && Math.abs(y - that.data.touchy) < 50) {      //右滑
        turn = "right";
      } else if (x - that.data.touchx < -50 && Math.abs(y - that.data.touchy) < 50) {   //左滑
        turn = "left";
      }
      if(y - that.data.touchy > 50 && Math.abs(x - that.data.touchx) < 50){ //下滑
        turn = "down";
      }else if(y - that.data.touchy < -50 && Math.abs(x - that.data.touchx) < 50){ //上滑
        turn="up";
      }
      //根据方向进行操作
      if(turn == 'down'){
        //下滑触发操作
      }
    },

参考 校园小程序 https://gitee.com/Kindear/yamako_procedure