vue+ant 弹窗可以拖动

通过自定义指令实现拖拽功能

在main.js里加入drag自定义指令

我自己测试时发现modal不管如何设置宽度,居中等,他的初始的left都为0,如果不设置好,容易出现点击后刚开始移动弹窗会偏移一段距离。

Vue.directive('drag', {
  bind(el) {
    // 获取弹窗头部
    const header = el.querySelector('.ant-modal-header')
    const modal = el.querySelector('.ant-modal')
    // 弹窗头部鼠标变为移动
    header.style.cursor = 'move'
    // 头部鼠标按下
    header.onmousedown = er => {
      // 得到初始位置
      // 初始位置left是0,top是modal的offsetTop
      const xx = modal.style.left ? parseInt(modal.style.left.slice(0, -2)) : 0
      const yy = modal.style.top ? parseInt(modal.style.top.slice(0, -2)) : modal.offsetTop
      const disX = er.clientX - xx
      const disY = er.clientY - yy

      document.onmousemove = e => {
        //距离 为 移动的位置-初始位置
        const left = e.clientX - disX
        const top = e.clientY - disY
        // 设置整个弹窗的距左距右位置
        modal.style.left = left + 'px'
        modal.style.top = top + 'px'
      }
      document.onmouseup = () => {
        document.onmousemove = null
        document.onmouseup = null
      }
    }
  }
})

 在modal使用了centered时会出现移动的一瞬间弹窗偏移严重的问题,而且弹窗上下居中的class名字在这里拿不到,所以只能再建一个dragcenter自定义指令。

// 自定义代码实现弹窗拖动效果  modal居中时
Vue.directive('dragcenter', {
  bind(el) {
    // ant-modal-centered在这里取不到
    // const centered = el.querySelector('ant-modal-centered')
    // console.log('centered', centered)
    
    // 获取弹窗头部
    const header = el.querySelector('.ant-modal-header')
    const modal = el.querySelector('.ant-modal')
    // 弹窗头部鼠标变为移动
    header.style.cursor = 'move'
    // 头部鼠标按下
    header.onmousedown = er => {
      // 得到初始位置
      // 居中的话 初始位置为0或已经移动过的位置
      const disX = modal.style.left ? parseInt(modal.style.left.slice(0, -2)) : 0
      const disY = modal.style.top ? parseInt(modal.style.top.slice(0, -2)) : 0
      document.onmousemove = e => {
      //距离 为 移动的位置-初始位置
      const left = disX + e.clientX - er.clientX
      const top = disY + e.clientY - er.clientY
      // 设置整个弹窗的距左距右位置
      modal.style.left = left + 'px'
      modal.style.top = top + 'px'
      }
      document.onmouseup = () => {
      document.onmousemove = null
      document.onmouseup = null
      }
    }
  }
})

使用时modal未使用centered则用v-drag,使用centered时则用v-dragcenter。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值