以下是一个基本的实现任意拖动的按钮的uniapp小程序代码:

<template>
  <view class="container">
    <view class="button" :style="buttonStyle" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd">拖动我</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      startX: 0, // 初始触摸点X坐标
      startY: 0, // 初始触摸点Y坐标
      buttonX: 0, // 按钮X坐标
      buttonY: 0, // 按钮Y坐标
      buttonWidth: 100, // 按钮宽度
      buttonHeight: 50, // 按钮高度
      containerWidth: 0, // 容器宽度
      containerHeight: 0 // 容器高度
    }
  },
  computed: {
    buttonStyle() {
      return {
        position: 'absolute',
        left: `${this.buttonX}px`,
        top: `${this.buttonY}px`,
        width: `${this.buttonWidth}px`,
        height: `${this.buttonHeight}px`
      }
    }
  },
  mounted() {
    // 获取容器宽高
    const rect = uni.createSelectorQuery().in(this).select('.container').boundingClientRect(data => {
      this.containerWidth = data.width
      this.containerHeight = data.height
    }).exec()
  },
  methods: {
    onTouchStart(e) {
      // 记录初始触摸点坐标
      this.startX = e.touches[0].clientX
      this.startY = e.touches[0].clientY
    },
    onTouchMove(e) {
      // 计算按钮新坐标
      const moveX = e.touches[0].clientX - this.startX
      const moveY = e.touches[0].clientY - this.startY
      let buttonX = this.buttonX + moveX
      let buttonY = this.buttonY + moveY
      // 判断按钮是否超出容器边界
      if (buttonX < 0) {
        buttonX = 0
      }
      if (buttonX + this.buttonWidth > this.containerWidth) {
        buttonX = this.containerWidth - this.buttonWidth
      }
      if (buttonY < 0) {
        buttonY = 0
      }
      if (buttonY + this.buttonHeight > this.containerHeight) {
        buttonY = this.containerHeight - this.buttonHeight
      }
      // 更新按钮坐标
      this.buttonX = buttonX
      this.buttonY = buttonY
      // 更新初始触摸点坐标
      this.startX = e.touches[0].clientX
      this.startY = e.touches[0].clientY
    },
    onTouchEnd() {
      // 触摸结束,不需要做任何事情
    }
  }
}
</script>

<style>
.container {
  width: 100%;
  height: 100%;
  background-color: #f0f0f0;
}

.button {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #4285f4;
  color: #fff;
  font-size: 16px;
  border-radius: 4px;
}
</style>

在该代码中,我们使用了uniapp的@touchstart@touchmove@touchend事件来实现按钮的拖动效果。在onTouchStart事件中,我们记录了初始触摸点的坐标,然后在onTouchMove事件中计算了按钮新的坐标,并判断是否超出了容器的边界,最后更新了按钮的坐标。由于我们使用了绝对定位来布局按钮,因此我们需要使用计算属性来动态更新按钮的样式。在onTouchEnd事件中,我们没有做任何事情,因为拖动结束时不需要执行任何操作。

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

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

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