vue实现可拖拽图标,图标默认显示在右下角

<template>
    <div class="drag-ball" :style="ballStyle" @mousedown="handleMouseDown"></div>
</template>

<script>
  export default {
    data() {
      return {
        isDragging: false,
        ballPosition: { x: 0, y: 0 }, // 拖拽div初始位置
        startPosition: { x: 0, y: 0 }, // 鼠标按下时的位置
      };
    },
    computed: {
      ballStyle() {
        return {
          position: "absolute",
          right: `${this.ballPosition.x}px`,
          bottom: `${this.ballPosition.y}px`,
        };
      },
    },
    methods: {
      handleMouseDown(event) {
        this.isDragging = true;
        this.startPosition = { x: event.clientX, y: event.clientY };
        document.addEventListener("mousemove", this.handleMouseMove);
        document.addEventListener("mouseup", this.handleMouseUp);
      },
      handleMouseMove(event) {
        if (this.isDragging) {
          const diffX = event.clientX - this.startPosition.x;
          const diffY = event.clientY - this.startPosition.y;
          this.ballPosition = {
            x: this.ballPosition.x - diffX,
            y: this.ballPosition.y - diffY,
          };
          this.startPosition = { x: event.clientX, y: event.clientY };
          this.constrainToScreen();
        }
      },
      handleMouseUp() {
        this.isDragging = false;
        document.removeEventListener("mousemove", this.handleMouseMove);
        document.removeEventListener("mouseup", this.handleMouseUp);
      },
      constrainToScreen() {
        // 限制拖拽时在屏幕范围内
        const windowWidth = window.innerWidth;
        const windowHeight = window.innerHeight;
        const ballRadius = 50; // 假设悬浮球半径为50px

        if (this.ballPosition.x < ballRadius) {
          this.ballPosition.x = ballRadius;
        } else if (this.ballPosition.x > windowWidth - ballRadius) {
          this.ballPosition.x = windowWidth - ballRadius;
        }
        if (this.ballPosition.y < ballRadius) {
          this.ballPosition.y = ballRadius;
        } else if (this.ballPosition.y > windowHeight - ballRadius - 100) {
          this.ballPosition.y = windowHeight - ballRadius - 100;
        }
      },
    },
  };
</script>

<style lang="scss" scoped>
 .drag-ball {
    cursor: move;
    background: #ffffff;
    box-shadow: 0px 4px 30px 0px rgba(191, 212, 239, 1);
    border-radius: 20px;
    width: 50px;
    height: 50px;
    z-index: 999;
  }
</style>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值