微信小程序 拖拽監聽功能:
在軟件開發或者 APP應用開發的時候,經常會遇到拖拽監聽,最近自己學習微信小程序的知識,就想實現這樣的拖拽效果,這里就記錄下。
需要做個浮在scroll-view之上的button.嘗試了一下.
上GIF:

Android中也會有類似移動控件的操作.思路差不多.獲取到位移的X Y 的變量,給控件設置坐標.
1.index.wxml
../images/gundong.png" bindtap="ballClickEvent" style="bottom:{{ballBottom}}px;right:{{ballRight}}px;" bindtouchmove="ballMoveEvent"> </image> 簡單的設置一張圖片,添加觸摸事件監聽.點擊事件監聽.根據觸摸事件獲取X Y位移,設置為image的位置
2.index.js
//index.js //獲取應用實例 var app = getApp() Page({ data: { ballBottom: 240, ballRight: 120, screenHeight: 0, screenWidth: 0, }, onLoad: function () { [javascript] view plain copy<span style="white-space:pre"> </span>//獲取屏幕寬高 var _this = this; wx.getSystemInfo({ success: function (res) { _this.setData({ screenHeight: res.windowHeight, screenWidth: res.windowWidth, }); } }); }, ballMoveEvent: function (e) { console.log('我被拖動了....') var touchs = e.touches[0]; var pageX = touchs.pageX; var pageY = touchs.pageY; console.log('pageX: ' + pageX) console.log('pageY: ' + pageY) //防止坐標越界,view寬高的一般 if (pageX < 30) return; if (pageX > this.data.screenWidth - 30) return; if (this.data.screenHeight - pageY <= 30) return; if (pageY <= 30) return;
//這里用right和bottom.所以需要將pageX pageY轉換 var x = this.data.screenWidth - pageX - 30; var y = this.data.screenHeight - pageY - 30; console.log('x: ' + x) console.log('y: ' + y) this.setData({ ballBottom: y, ballRight: x }); }, //點擊事件 ballClickEvent: function () { console.log('點擊了....') } }) 3.index.wxss
這里需要設置z-index
.image-style{ position: absolute; bottom: 240px; right: 100px; width: 60px; height: 60px; z-index: 100; } 新聞熱點
疑難解答