You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
crmeb/admin/src/directive/dialog/drag.js

58 lines
1.6 KiB

12 months ago
/**
* v-dialogDrag 弹窗拖拽终极稳定版
* 解决初始居中 + 按下闪烁偏移错误飞到右下角
*/
12 months ago
export default {
bind(el, binding) {
12 months ago
const value = binding.value
if (value === false) return
12 months ago
const dialogHeaderEl = el.querySelector('.el-dialog__header')
const dragDom = el.querySelector('.el-dialog')
12 months ago
if (!dialogHeaderEl || !dragDom) return
12 months ago
dialogHeaderEl.style.cursor = 'move'
12 months ago
// 初始化:绝对居中
dragDom.style.position = 'fixed'
dragDom.style.margin = '0'
dragDom.style.left = '50%'
dragDom.style.top = '50%'
dragDom.style.transform = 'translate(-50%, -50%)'
12 months ago
// 鼠标按下
dialogHeaderEl.onmousedown = (e) => {
e.preventDefault()
// 先拿到当前弹窗真实的 left / top去掉 translate 影响)
const currLeft = dragDom.getBoundingClientRect().left
const currTop = dragDom.getBoundingClientRect().top
// 按下瞬间立刻清除居中,重新设置真实 left top
dragDom.style.transform = 'none'
dragDom.style.left = currLeft + 'px'
dragDom.style.top = currTop + 'px'
// 计算正确偏移(这是唯一不飞的算法)
const disX = e.clientX - currLeft
const disY = e.clientY - currTop
// 移动
document.onmousemove = (e) => {
let left = e.clientX - disX
let top = e.clientY - disY
dragDom.style.left = left + 'px'
dragDom.style.top = top + 'px'
}
// 抬起
document.onmouseup = () => {
document.onmousemove = null
document.onmouseup = null
}
12 months ago
}
}
}