自学内容网 自学内容网

vue+ant解决弹窗可以拖动的问题

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

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

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 => {
      // 得到初始位置
      const disX = er.clientX - modal.offsetLeft
      const disY = er.clientY - modal.offsetTop

      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 ? modal.style.left : 0
      const disY = modal.style.top ? modal.style.top : 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。


原文地址:https://blog.csdn.net/qq_56995244/article/details/142887332

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!