小程序可拖動懸浮窗

小程序可拖動懸浮窗

在小程序中設置一個可拖動的懸浮窗,代碼如下:
wxml代碼:

  <view class="view" style=" top:{{top}}px;left:{{left}}px;margin: 0% 0rpx 0rpx 0%;" bindtouchmove="setTouchMove">
    <view>
    <image style="height:120rpx;width:120rpx;border-radius:50%" src="./touxiang.png"></image>
    </view>
  </view>

wxss代碼:

.view{
position: fixed ; /*相對定位*/
height:120rpx;
width:120rpx;
border-radius:50%;
color: white;
text-align: center;
}

js代碼:

 setTouchMove: function (e) {
    console.log("---------------- e.touches[0].clientX----------------8==" + e.touches[0].clientX)
    console.log("---------------- e.touches[0].clientY----------------8=======" + e.touches[0].clientY)
     //此處clientY與clientX爲拖動懸浮窗超過設定的大小會返回默認顯示位置
    if (e.touches[0].clientX < 350 && e.touches[0].clientY < 550 && e.touches[0].clientX > 0 && e.touches[0].clientY > 0){
      this.setData({
      left: e.touches[0].clientX,
      top: e.touches[0].clientY
    })
    } else {
         this.setData({
            left: 0, //默認顯示位置 left距離
            top: 250  //默認顯示位置 top距離
        })
    }
  },

此外,js代碼如果添加至app.js調用使用的話,代碼需要做一些修改,代碼如下:

 setTouchMove: function (e,that) {
    console.log("---------------- e.touches[0].clientX----------------8==" + e.touches[0].clientX)
    console.log("---------------- e.touches[0].clientY----------------8=======" + e.touches[0].clientY)
    //此處clientY與clientX爲拖動懸浮窗超過設定的大小會返回默認顯示位置
    if (e.touches[0].clientX < 350 && e.touches[0].clientY < 550 && e.touches[0].clientX > 0 && e.touches[0].clientY > 0) {
      that.setData({
        left: e.touches[0].clientX,
        top: e.touches[0].clientY
      })
    } else {
      that.setData({
        left: 0, //默認顯示的位置 left距離
        top: 250 //默認顯示的位置 top距離
      })
    }
  },

主要在function(e)這裏增加了一個參數,改變爲function(e,that),設置參數的setData也變爲了that而不是this.
代碼是借用其他CSDN博主的:
原鏈接:原博主鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章