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

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* v-dialogDrag 弹窗拖拽(终极稳定版)
* 解决:初始居中 + 按下闪烁、偏移错误、飞到右下角
*/
export default {
bind(el, binding) {
const value = binding.value
if (value === false) return
const dialogHeaderEl = el.querySelector('.el-dialog__header')
const dragDom = el.querySelector('.el-dialog')
if (!dialogHeaderEl || !dragDom) return
dialogHeaderEl.style.cursor = 'move'
// 初始化:绝对居中
dragDom.style.position = 'fixed'
dragDom.style.margin = '0'
dragDom.style.left = '50%'
dragDom.style.top = '50%'
dragDom.style.transform = 'translate(-50%, -50%)'
// 鼠标按下
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
}
}
}
}