原生JS小程序拖动组件

709 阅读2分钟

**原生JS小程序拖动组件 **

功能要求:首页设置进行中订单入口,该入口可长按并自由滑动,当手指松开的时候会判断改图标离屏幕哪边比较近,并自动吸附到左边或者右边

整理思路:第一次写类似组件,查阅了一下官方文档,发现今年3月更新了一个叫movable-view的组件,应该也能实现我想要的功能,但是鉴于想要实现长按拖动和自动吸附的功能,还想把该组件写的更易于引用,就决定自己写了

效果:

WXML代码

组件代码
<view class='customer' bind:longpress="longPress" catch:touchmove="touchMove" catch:touchend="touchEnd" style="top:{{top}}rpx;left:{{left}}rpx">
  <view class='index-bg' bindtap="miniPageChange" data-miniPath="/pages/order/process/index" style="{{left<260?'border-radius: 0rpx 100rpx 100rpx 0;':''}}">
  <view class='bg-text ell'>进行中订单</view>
</view>
  <slot></slot>
</view>

JS代码

Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    top: 800,
    left: 570,
    touch:false
  },

  /**
   * 组件的方法列表
   */
  methods: {
    longPress(e) {
      this.setData({
        touch: true
      });
      wx.vibrateShort();
    },
    //组件实现拖动效果
    touchMove: function (e) {
      if (!this.data.touch) return;
      var that = this
      if (e.touches[0].clientX < (wx.getSystemInfoSync().windowWidth - 96) && e.touches[0].clientX > 0 && e.touches[0].clientY < (wx.getSystemInfoSync().windowHeight - 20) && e.touches[0].clientY > 20) {
        wx.getSystemInfo({
          success: function (res) {
            let X = (e.touches[0].clientX * (750 / res.windowWidth));
            // 将高度乘以换算后的该设备的rpx与px的比例
            let Y = (e.touches[0].clientY * (750 / res.windowWidth));
            // 将高度乘以换算后的该设备的rpx与px的比例
            that.setData({
              left: X,
              top: Y
            })
          }
        })

      }
    },
    touchEnd: function (e) {
      if (!this.data.touch) return;
      this.setData({
        touch:false
      })
      let x = this.data.left
      if(x > 260){
        x = 554
      }else{
        x = 0
      }
      this.setData({
        left: x,
      })    

    },
    miniPageChange(e) {
      const url = e.currentTarget.dataset.minipath;
      wx.navigateTo({
        url,
      })
    },
  }
})

JSON代码

{
  "component": true,
  "usingComponents": {}
}

WXSS代码

.customer {
  position: fixed;
  z-index: 1000;
  width:200rpx;
  height: 200rpx;
}

.index-bg {
  position: absolute;
  right: 0;
  bottom: 168rpx;
  width: 200rpx;
  height: 80rpx;
  background-size: cover;
  background-color: rgba(255, 214, 67, 0.9);
  border-radius: 100rpx 0 0 100rpx;
}

.index-bg .bg-text {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  /* width: 300rpx; */
  height: 40rpx;
  font-size: 28rpx;
  font-family: PingFangSC-Regular;
  font-weight: 400;
  color:rgba(0, 0, 0, 0.8);
}


首页引用插件

JSON代码
"usingComponents": {
    "custom": "/components/custom/index"
  }
  
WXML代码
<custom></custom>