微信小程序拖拽组件

841 阅读2分钟

作用

该代码示例实现了一个小程序组件,通过拖动组件可以实现元素的移动和位置的调整。

实现

  1. 在wxml中,创建一个视图(view)元素,并设置class为drag,并使用样式绑定transformtranslateXtranslateY 应用到视图上,这样可以根据 translateX 和 translateY 的值来实现元素的移动。同时,绑定 bindtouchstart 事件和 catchtouchmove 事件,分别用于开始触摸和触摸移动时的处理。
<view class="drag" style ="transform: translate({{translateX}}px, {{translateY}}px)" bindtouchstart="touchStart" catchtouchmove="touchMove">
  <slot></slot>
</view>
  1. 在css中,为class为drag的元素设置positionfixedtop为0,right为10px,以确保它始终位于页面的右上角。
.drag{
  position: fixed;
  top: 0;
  right: 10px;
}
  1. 在js中,定义了一些变量用于存储拖动过程中的相关信息,如translateXtranslateY表示位移距离,distance表示双指接触点的距离,startMove存储起始位移距离,startTouches存储起始点的touch数组。同时,定义了两个方法,touchStart用于处理touchstart事件,获取起始位移距离和起始点的touch数组;touchMove用于处理touchmove事件,根据起始位移距离和当前触摸点的位置计算出新的位移距离,并更新translateXtranslateY的值。
/**
   * 组件的初始数据
   */
  data: {
    translateX: 0, // 位移x坐标 单位px
    translateY: 0, // 位移y坐标 单位px
    distance: 0, // 双指接触点距离
    startMove: { // 起始位移距离
      x: 0,
      y: 0,
    },
    startTouches: [] // 起始点touch数组
  },

  /**
   * 组件的方法列表
   */
  methods: {
    touchStart(e) {
      const touches = e.touches
      const { translateX, translateY } = this.data
      const { pageX, pageY } = touches[0]
      this.data.startMove = {
        x: pageX - translateX,
        y: pageY - translateY
      }
      this.data.startTouches = touches
    },
    touchMove(e) {
      const touches = e.touches
      const { pageX: onePageX, pageY: onePageY } = touches[0]
      const { startMove } = this.data
      this.setData({
        translateX: onePageX - startMove.x,
        translateY: onePageY - startMove.y
      })
    },
  }

引用

  • 在使用该组件的页面的json文件中,通过usingComponents字段引入了名为drag的组件,指定了组件所在的路径。
{
  "usingComponents": {
    "drag": "../drag/drag"
  },
  "component": true
}

使用

  • 在使用该组件的页面的wxml文件中,将需要拖动的元素放置在drag组件的内部,即用drag标签包裹住需要拖动的元素。
<drag>
    <image src='{{item.homeConImg}}' class='pictrue' bindtap="homeConBtn"></image>
</drag>

总结

使用上述代码,可以实现对元素的拖动操作。当用户触摸并移动被包裹在drag组件内的元素时,元素会跟随手指移动。需要注意的是,为了确保拖动操作正常进行,touchstart事件需要使用bindtouchstart绑定,touchmove事件需要使用catchtouchmove绑定,而如果拖动元素上还有其他交互操作如tap事件,则需要使用bindtap绑定。