1. 程式人生 > >微信小程式 監聽手勢滑動切換頁面

微信小程式 監聽手勢滑動切換頁面

1.對應的xml裡寫上手勢開始、滑動、結束的監聽:

<view class="touch"  bindtouchstart="touchStart" bindtouchmove="touchMove" bindtouchend="touchEnd" ></view>

2.Js:

var touchDot = 0;//觸控時的原點
var time = 0;// 時間記錄,用於滑動時且時間小於1s則執行左右滑動
var interval = "";// 記錄/清理時間記錄
Page({
  data: {...}
      })

Page({
  data: {
         ...
  },
  // 觸控開始事件
  touchStart: function (e) {
    touchDot = e.touches[0].pageX; // 獲取觸控時的原點
    // 使用js計時器記錄時間  
    interval = setInterval(function () {
      time++;
    }, 100);
  },
  // 觸控移動事件
  touchMove: function (e) {
    var touchMove = e.touches[0].pageX;
    console.log("touchMove:" + touchMove + " touchDot:" + touchDot + " diff:" + (touchMove - touchDot));
    // 向左滑動  
    if (touchMove - touchDot <= -40 && time < 10) {
      wx.switchTab({
        url: '../左滑頁面/左滑頁面'
      }); 
    }
    // 向右滑動
    if (touchMove - touchDot >= 40 && time < 10) {
      console.log('向右滑動');
      wx.switchTab({
        url: '../右滑頁面/右滑頁面'
      }); 
    }
  },
  // 觸控結束事件
  touchEnd: function (e) {
    clearInterval(interval); // 清除setInterval
    time = 0;
  },
.
.
.
})