小程序端悬浮按钮可以拖拽的demo

2024-01-09  本文已影响0人  泪滴在琴上
<template>
  <div class="floating-button"
    :style="{ position: 'fixed', right: buttonStyle.right, top: buttonStyle.top, transform: buttonStyle.transform }"
    @touchstart="startDrag" @touchmove.prevent="onDrag" @touchend="endDrag" @touchcancel="endDrag" @click="gotoAI">
    <img src="../../../static/images/product/kefu1.png" />
    <p>智能客服</p>
  </div>
</template>
<script>
export default {
  data() {
    return {
      buttonStyle: {
        position: "fixed",
        right: "2px",
        top: "400px",
        zIndex: 999,
      },
      dragging: false,
      initialX: 0,
      initialY: 0,
      offsetX: 0,
      offsetY: 0,
    };
  },
  methods: {
    gotoAI() {
      let url = "../../pages/customMessage/main"
      mpvue.navigateTo({ url });
    },
    startDrag(event) {
      event.preventDefault(); // 阻止默认行为
      this.dragging = true;
      // 记录初始触摸位置
      this.initialX = event.touches[0].clientX;
      this.initialY = event.touches[0].clientY;

      // 记录当前偏移量
      this.offsetX = parseInt(this.buttonStyle.right.slice(0, -2));
      this.offsetY = parseInt(this.buttonStyle.top.slice(0, -2));
    },
    onDrag(event) {
      event.preventDefault(); // 阻止默认行为
      if (this.dragging) {
        // 计算偏移量
        const deltaX = event.touches[0].clientX - this.initialX;
        const deltaY = event.touches[0].clientY - this.initialY;
        // 更新按钮位置
        this.buttonStyle.right = `${this.offsetX - deltaX}px`;
        this.buttonStyle.top = `${this.offsetY + deltaY}px`;
      }
    },
    endDrag(event) {
      event.stopPropagation();
      this.dragging = false;
    },
  }
};
</script>
<style scoped>
.floating-button {
  width: 100rpx;
  height: 124rpx;
  opacity: 0.9;
  border-radius: 10rpx 0 0 10rpx;
  background: linear-gradient(180deg, rgba(54, 113, 155, 1) 0%, rgba(10, 46, 56, 1) 100%);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.floating-button img {
  width: 60rpx;
  height: 60rpx;
  display: block;
  margin-bottom: 10rpx;
}

.floating-button p {
  font-size: 20rpx;
  font-weight: 400;
  letter-spacing: 0px;
  color: rgba(249, 249, 249, 1);
  text-align: center;
}
</style>

上一篇 下一篇

猜你喜欢

热点阅读