小程序--可移动的悬浮按钮

.wxml里

  <button catchtouchmove="buttonMove" bindtouchstart="buttonStart" bindtouchend="buttonEnd" catchtap="evaluateEvt" style="top:{{buttonTop}}px;left:{{buttonLeft}}px;width: 80px;height:50px;position:fixed;background:#ff6700;line-height:50px;font-size: 28rpx;;color:#fff;padding: 0;font-weight: 500;">
  <view>课程建议</view>
  </button>



.js里

let startPoint;

data: {
    buttonTop: 0,
    buttonLeft: 0
  },
  onLoad: function(options) {
    // 计算drawer高度,占满window
    let that = this;
    //  高度自适应
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          buttonTop:  res.windowHeight - 120, //悬浮按钮初始位置
          buttonLeft:  res.windowWidth - 100 //悬浮按钮初始位置
        });
      }
    });
  },
    
    buttonStart: function (e) {
    startPoint = e.touches[0]
  },
  buttonMove: function (e) {
    let endPoint = e.touches[e.touches.length - 1];
    let translateX = endPoint.clientX - startPoint.clientX;
    let translateY = endPoint.clientY - startPoint.clientY;
    startPoint = endPoint;
    let buttonTop = this.data.buttonTop + translateY;
    let buttonLeft = this.data.buttonLeft + translateX;
    //判断是移动否超出屏幕
    if (buttonLeft + 80 >= this.data.windowWidth){
      buttonLeft = this.data.windowWidth - 80;
    }
    if (buttonLeft <= 0){
      buttonLeft = 0;
    }
    if (buttonTop <= 0){
      buttonTop = 0
    }
    if (buttonTop + 100 >= this.data.windowHeight){
      buttonTop = this.data.windowHeight - 100;
    }
    this.setData({
      buttonTop: buttonTop,
      buttonLeft: buttonLeft
    })
  },
  buttonEnd: function (e) {
    
  }

// 点击悬浮按钮
  evaluateEvt(){
    this.setData({
      // dialogShow: true
    })
  },

 

小程序--可移动的悬浮按钮

上一篇:小程序常用基础语法精选


下一篇:微信JS-SDK分享接口实例开发(nodeJS)