函数封装
function handleDialogDrag (dragTarget, dragMain) {
dragTarget.style.cursor = 'move';
dragTarget.onmousedown = e => {
if (e.target.classList.contains('icon')) return;
const startX = e.clientX;
const startY = e.clientY;
const screenWidth = document.body.clientWidth;
const screenHeight = document.body.clientHeight;
const dragMainWidth = dragMain.offsetWidth;
const dragMainHeight = dragMain.offsetHeight;
const leftMaxDistance = dragMain.offsetLeft;
const rightMaxDistance = screenWidth - dragMain.offsetLeft - dragMainWidth;
const topMaxDistance = dragMain.offsetTop;
const bottomMaxDistance = screenHeight - dragMain.offsetTop - dragMainHeight;
let { left, top } = getComputedStyle(dragMain, null);
if (left.includes('%')) {
left = document.body.clientWidth * (parseInt(left) / 100);
top = document.body.clientHeight * (parseInt(top) / 100);
} else {
left = parseInt(left);
top = parseInt(top);
}
document.onmousemove = function(e) {
let moveLeft = e.clientX - startX;
let moveTop = e.clientY - startY;
if (-moveLeft > leftMaxDistance) {
moveLeft = -leftMaxDistance;
} else if (moveLeft > rightMaxDistance) {
moveLeft = rightMaxDistance;
}
if (-moveTop > topMaxDistance) {
moveTop = -topMaxDistance;
} else if (moveTop > bottomMaxDistance) {
moveTop = bottomMaxDistance;
}
dragMain.style.left = moveLeft + left + 'px';
dragMain.style.top = moveTop + top + 'px';
};
document.onmouseup = function(e) {
document.onmousemove = null;
document.onmouseup = null;
};
}
}
使用,以el-dialog为例
dom结构
<el-dialog
v-dialog-drag
append-to-body
title="提示"
:visible.sync="dialogVisible"
width="30%"
:before-close="handleClose">
<span>这是一段信息</span>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="dialogVisible = false">确 定</el-button>
</span>
</el-dialog>
定义指令
directives: {
dialogDrag: {
bind(el) {
handleDialogDrag(el.querySelector('.el-dialog__header'), el.querySelector('.el-dialog'));
}
}
},