欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > vue+ant解决弹窗可以拖动的问题

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

2025/2/23 16:47:46 来源:https://blog.csdn.net/qq_56995244/article/details/142887332  浏览:    关键词: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.offsetLeftconst disY = er.clientY - modal.offsetTopdocument.onmousemove = e => {//距离 为 移动的位置-初始位置const left = e.clientX - disXconst top = e.clientY - disY// 设置整个弹窗的距左距右位置modal.style.left = left + 'px'modal.style.top = top + 'px'}document.onmouseup = () => {document.onmousemove = nulldocument.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 : 0const disY = modal.style.top ? modal.style.top : 0document.onmousemove = e => {//距离 为 移动的位置-初始位置const left = disX + e.clientX - er.clientXconst top = disY + e.clientY - er.clientY// 设置整个弹窗的距左距右位置modal.style.left = left + 'px'modal.style.top = top + 'px'}document.onmouseup = () => {document.onmousemove = nulldocument.onmouseup = null}}}
})

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词