Function encapsulation
/** dialog move handler *@param {HTMLObjectElement} DragTarget Target to drag *@param {HTMLObjectElement} DragMain Drags the moving body */
function handleDialogDrag (dragTarget, dragMain) {
dragTarget.style.cursor = 'move';
// Mouse down
dragTarget.onmousedown = e= > {
// Mouse over the button does not trigger movement
if (e.target.classList.contains('icon')) return;
// Mouse start position
const startX = e.clientX;
const startY = e.clientY;
// The current screen width and height
const screenWidth = document.body.clientWidth;
const screenHeight = document.body.clientHeight;
// Move the body width and height
const dragMainWidth = dragMain.offsetWidth;
const dragMainHeight = dragMain.offsetHeight;
// The maximum distance to move the subject left and right
const leftMaxDistance = dragMain.offsetLeft;
const rightMaxDistance = screenWidth - dragMain.offsetLeft - dragMainWidth;
// Move the maximum distance that the subject moves up and down
const topMaxDistance = dragMain.offsetTop;
const bottomMaxDistance = screenHeight - dragMain.offsetTop - dragMainHeight;
// Move the current left top value of the subject
let { left, top } = getComputedStyle(dragMain, null);
if (left.includes(The '%')) {
left = document.body.clientWidth * (parseInt(left) / 100);
top = document.body.clientHeight * (parseInt(top) / 100);
} else {
left = parseInt(left);
top = parseInt(top);
}
// Mouse movement
document.onmousemove = function(e) {
let moveLeft = e.clientX - startX;
let moveTop = e.clientY - startY;
// boundary processing
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';
};
// Release the mouse
document.onmouseup = function(e) {
document.onmousemove = null;
document.onmouseup = null; }; }}Copy the code
, take el-Dialog as an example
Dom structure
<el-dialog
v-dialog-drag
append-to-body
title="Tip"
:visible.sync="dialogVisible"
width="30%"
:before-close="handleClose">
<span>This is a piece of information</span>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">Take away</el-button>
<el-button type="primary" @click="dialogVisible = false">determine</el-button>
</span>
</el-dialog>
Copy the code
Define the instructions
directives: {
dialogDrag: {
bind(el) {
handleDialogDrag(el.querySelector('.el-dialog__header'), el.querySelector('.el-dialog')); }}},Copy the code