您好,登錄后才能下訂單哦!
怎么在微信小程序中實現一個可拖動的懸浮圖標?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
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,//這里定義按鈕的初始位置 }) } }) }, //可拖動懸浮按鈕點擊事件 btn_Suspension_click:function(){ //這里是點擊購物車之后將要執(zhí)行的操作 wx.showToast({ title: '點擊成功', icon:'success', duration:1000 }) }, //以下是按鈕拖動事件 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:
<!--可拖動按鈕控件表--> <!--buttonStart和buttonEnd一定不能用catch事件,否則按鈕點擊事件會失效--> <view class="btn_Suspension" bindtap="btn_Suspension_click" catchtouchmove="buttonMove" bindtouchstart="buttonStart" bindtouchend="buttonEnd" > <image class="Suspension_logo" src="../images/Suspension.png"></image><!--這里是按鈕圖標,下載地址會在文章底部說明--> <view wx:if="{{corner_data==0}}"></view> <view wx:else> <view class="cornorMark"> <text>{{corner_data}}</text> </view> </view> </view>
wxss:
Page{ background: #f5f5f5; } /**可拖動懸浮按鈕樣式表**/ .btn_Suspension{ position: fixed; height: 100rpx; width: 100rpx; background-color: rgba(255, 255, 255, 0.755); border-radius: 100%; display: flex; align-items: center; justify-content: center; z-index: 99999; box-shadow: 1px 0px 1px 1px #ede7e7; } .Suspension_logo{ position:absolute; height:50%; width:50%; left:23%; top:27% } .cornorMark{ position:absolute; background: rgb(242, 109, 38); border:1px solid rgb(242, 109, 38); border-radius: 100px; width:30rpx; height:30rpx; top:-17rpx; right:3rpx; color:#fff; font-size: 12px; text-align: center; } .cornorMark text{ position:absolute; width:100%; left:0%; text-align: center; top:-1px; }
看完上述內容,你們掌握怎么在微信小程序中實現一個可拖動的懸浮圖標的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。