小程序可拖动悬浮窗

小程序可拖动悬浮窗

在小程序中设置一个可拖动的悬浮窗,代码如下:
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博主的:
原链接:原博主链接

猜你喜欢

转载自blog.csdn.net/qingmu_hehui/article/details/82797331