以下是一个简单的微信小程序,实现了一个任意拖动的按钮。该小程序使用了原生组件 <movable-area><movable-view>,实现了在页面上拖动按钮的功能,并且兼容了不同尺寸的手机屏幕。

<view class="container">
  <movable-area class="movable-area">
    <movable-view class="movable-view" direction="all" damping="100" friction="10" x="{{x}}" y="{{y}}" bindchange="onChange">
      <button class="button" bindtouchstart="onTouchStart" bindtouchmove="onTouchMove" bindtouchend="onTouchEnd">Drag me!</button>
    </movable-view>
  </movable-area>
</view>
.container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.movable-area {
  width: 100%;
  height: 100%;
}

.movable-view {
  position: relative;
  width: 100px;
  height: 100px;
  background-color: #07c160;
  border-radius: 50%;
}

.button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
  font-size: 16px;
  border: none;
  background-color: transparent;
  cursor: move;
}
Page({
  data: {
    x: 0,
    y: 0
  },
  onTouchStart: function (e) {
    this.startX = e.touches[0].pageX;
    this.startY = e.touches[0].pageY;
  },
  onTouchMove: function (e) {
    var moveX = e.touches[0].pageX - this.startX;
    var moveY = e.touches[0].pageY - this.startY;
    this.setData({
      x: this.data.x + moveX,
      y: this.data.y + moveY
    });
    this.startX = e.touches[0].pageX;
    this.startY = e.touches[0].pageY;
  },
  onTouchEnd: function () {
    // do something when touch ends
  },
  onChange: function (e) {
    // do something when position changes
  }
})

在这个示例中,我们首先定义了一个 <movable-area> 组件,它设置了整个页面的可移动范围。然后,我们在 <movable-area> 中定义了一个 <movable-view> 组件,它是一个可移动的视图容器,它可以在其中放置一个或多个子组件。在这个例子中,我们只放置了一个 <button> 组件。

<movable-view> 中,我们使用了 xy 属性来设置按钮的初始位置。我们还绑定了 bindchange 事件,它会在按钮位置改变时触发。在 onChange 方法中,我们可以处理位置的变化,例如更新按钮的位置、保存位置信息等。

为了实现拖动功能,我们在按钮上绑定了 bindtouchstartbindtouchmovebindtouchend 事件。在 onTouchStart 方法中,我们保存了触摸开始时的位置。在 onTouchMove 方法中,我们计算出触摸移动的距离,然后更新按钮的位置。最后,在 onTouchEnd 方法中,我们可以做一些清理工作,例如保存按钮的最终位置。

微信小程序写一个任意拖动的按钮兼容

原文地址: https://www.cveoy.top/t/topic/bpfP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录