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中的元素位置參數