微信小程序實現圖片拖拽


js代碼

var startPoint
Page({
  data: {
    //按鈕位置參數
    buttonTop: 0,
    buttonLeft: 0,
    windowHeight: '',
    windowWidth: '',
    //角標顯示數字
    corner_data:0,
  },
  onLoad:function(){
    //定義角標數字
    this.setData({
      corner_data:3
    })
    
    var that =this;
    wx.getSystemInfo({
      success: function (res) {
        console.log(res);
        // 屏幕寬度、高度
        console.log('height=' + res.windowHeight);
        console.log('width=' + res.windowWidth);
        // 高度,寬度 單位為px
        that.setData({
          windowHeight:  res.windowHeight,
          windowWidth:  res.windowWidth,
          buttonTop:res.windowHeight*0.70,//這里定義按鈕的初始位置
          buttonLeft:res.windowWidth*0.70,//這里定義按鈕的初始位置
        })
      }
    })
  },
 
  //以下是按鈕拖動事件
  buttonStart: function (e) {
    startPoint = e.touches[0]//獲取拖動開始點
  },
  buttonMove: function (e) {
    var endPoint = e.touches[e.touches.length - 1]//獲取拖動結束點
    //計算在X軸上拖動的距離和在Y軸上拖動的距離
    var translateX = endPoint.clientX - startPoint.clientX
    var translateY = endPoint.clientY - startPoint.clientY
    startPoint = endPoint//重置開始位置
    var buttonTop = this.data.buttonTop + translateY
    var buttonLeft = this.data.buttonLeft + translateX
    //判斷是移動否超出屏幕
    if (buttonLeft+50 >= this.data.windowWidth){
      buttonLeft = this.data.windowWidth-50;
    }
    if (buttonLeft<=0){
      buttonLeft=0;
    }
    if (buttonTop<=0){
      buttonTop=0
    }
    if (buttonTop + 50 >= this.data.windowHeight){
      buttonTop = this.data.windowHeight-50;
    }
    this.setData({
      buttonTop: buttonTop,
      buttonLeft: buttonLeft
    })
  },
  buttonEnd: function (e) {
  }
})

wxml代碼

<view class="btn_Suspension" bindtap="btn_Suspension_click" catchtouchmove="buttonMove" bindtouchstart="buttonStart" bindtouchend="buttonEnd" style="top:{{buttonTop}}px;left:{{buttonLeft}}px;">
    <image class="Suspension_logo" src="XXXXXXX.png"></image>
    
    </view>
  </view>

vue的拖拽原理也是一樣的

1.監聽拖拽開始事件獲取初始位置

2.監聽移動事件並獲取x,y軸與初始位置的差

3.改變在data中的元素位置參數


免責聲明!

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



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