ant-desgin vue 弹窗拖拽功能实现

 实现拖拽功能,主要有以下几个步骤:

1. 鼠标点击时获取鼠标的坐标,并开始监听鼠标的移动和鼠标的松开动作

2. 鼠标移动时获取当前坐标,并计算相对于鼠标点击时坐标的偏移值,并修改弹窗的偏移量

3. 鼠标松开时停止所有监听,并保存弹窗当前的位置

直接上代码:

<template>
  <a-modal
    v-model:visible="modelVisible"
    :style="style"
  >
    <template #title>
        <-- 此处我只在弹窗的title部分添加了拖拽功能-->
      <div style="padding: 16px 24px" @mousedown="mouseDown" @mouseup="mouseUp">
        <slot name="title"></slot>
      </div>
    </template>
    <template #footer>
      <slot name="footer"></slot>
    </template>
    <slot></slot>
  </a-modal>
</template>
<script>
import { defineComponent } from 'vue';
export default defineComponent({
  data () {
    return {
      modelVisible: false,
      style: null,
      initX: null,
      initY: null,
      left: 0,        //移动时相对于鼠标点击时坐标的偏移位置
      top: 0,
      lastleft: 0,     // 每次拖拽后弹窗的位置
      lasttop: 0
    }
  },
  methods: {
    mouseDown (e) {
      this.initX = e.clientX;
      this.initY = e.clientY;
      document.addEventListener("mousemove", this.mouseMove, false)
      document.addEventListener("mouseup", this.mouseUp, false)
    },
    mouseUp () {
      //拖拽后弹窗最后一次所在位置为前一次拖拽最后的位置加上这次拖拽的偏移量
      this.lastleft = this.lastleft + this.left;       
      this.lasttop = this.lasttop + this.top;
      this.style = "left:" + this.lastleft + "px;margin-top: " + this.lasttop + "px"
      document.removeEventListener("mousemove", this.mouseMove, false)
      document.removeEventListener("mouseup", this.mouseUp, false)
      this.initX = null;
      this.initY = null;
    },
    mouseMove (e) {
      this.left = (e.clientX - this.initX);
      this.top = (e.clientY - this.initY)
      this.style = "left:" + this.lastleft + "px;margin-top: " + this.lasttop + "px" + ";transform:translate(" + this.left + "px," + this.top + "px)"
    },
  }
})
</script>
<style lang="scss">
.ant-modal-header {
  padding: 0;
}
</style>

此代码是基于vue3写的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值