微信小程序~觸摸相關事件(拖拽操作、手勢識別、多點觸控)


touchstart     手指觸摸動作開始
touchmove    手指觸摸后移動
touchcancel  手指觸摸動作被打斷,如來電提醒,彈窗
touchend      手指觸摸動作結束

拖拽操作案例1:

  注意按鈕拖出屏幕邊緣處理

<view id="id" bindtouchmove="handletouchmove" class='demo' style='top:{{ballTop}}px; left: {{ballLeft}}px'></view>
page{background:red}
.demo{ width:60px; height:60px; background:#545345;box-shadow:2px 2px 10px #AAA;border-radius: 20px;position: absolute; }
Page({
  data: {
    ballTop: 0,
    ballLeft: 0,
    screenHeight: 0,
    screenWidth: 0
  },
  onLoad: function () {
    // 一是會將按鈕拖出屏幕邊緣,
    // 二是按鈕始終在鼠標右下方。
    // 獲取屏幕寬高
    var _this = this;
    wx.getSystemInfo({
      success: function (res) {
        _this.setData({
          screenHeight: res.windowHeight,
          screenWidth: res.windowWidth,
        });
      }
    });
  },
  handletouchmove: function (event) {
    // console.log(event)
    let pageX = event.touches[0].pageX;
    let pageY = event.touches[0].pageY;
    //屏幕邊界判斷   中心點位置
    if (pageX < 30 || pageY < 30)
      return;
    if (pageX > this.data.screenWidth - 30)
      return;
    if (pageY > this.data.screenHeight - 30)
      return;

    //左上角位置
    this.setData({
      ballTop: event.touches[0].pageY - 30,
      ballLeft: event.touches[0].pageX - 30,
    });

  }
})

手勢識別案例2:

<view id="id" bindtouchstart="handletouchtart" bindtouchmove="handletouchmove"
style="width:100%px;height:80px;line-height:80px;color:#fff;text-align:center; background:red">
{{text}} 
</view>
Page({
  data: {
    lastX: 0,
    lastY: 0,
    text: "沒有滑動",
  },
  handletouchmove: function (event) {
    // console.log(event)
    let currentX = event.touches[0].pageX
    let currentY = event.touches[0].pageY
    let tx = currentX - this.data.lastX
    let ty = currentY - this.data.lastY
    let text = ""
    
    if (Math.abs(tx) > Math.abs(ty)) {
      //左右方向滑動
      if (tx < 0)
        text = "向左滑動"
      else if (tx > 0)
        text = "向右滑動"
    }
    else {
      //上下方向滑動
      if (ty < 0)
        text = "向上滑動"
      else if (ty > 0)
        text = "向下滑動"
    }

    //將當前坐標進行保存以進行下一次計算
    this.data.lastX = currentX
    this.data.lastY = currentY
    this.setData({
      text: text,
    });

  },
  handletouchtart: function (event) {
    // console.log(event)
    // 賦值
    this.data.lastX = event.touches[0].pageX
    this.data.lastY = event.touches[0].pageY
  }
})

多點觸控案例3:

  根據相關功能可進行通過編輯器-遠程調試,如手指張開的操作,可以分別判斷兩個觸摸點的移動方向,比如靠左的觸摸點向左滑動,靠右的觸摸點向右滑動,即可判定為手指張開操作。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM