70 lines
1.9 KiB
JavaScript
70 lines
1.9 KiB
JavaScript
const moveModal = (elmnt) => {
|
||
console.log(elmnt);
|
||
var pos1 = 0,
|
||
pos2 = 0,
|
||
pos3 = 0,
|
||
pos4 = 0;
|
||
// 只在目標元素上監聽 mousedown,避免全域攔截
|
||
elmnt.addEventListener("mousedown", dragMouseDown, {
|
||
passive: false,
|
||
});
|
||
|
||
function dragMouseDown(e) {
|
||
console.log("dragMouseDown", e);
|
||
e = e || window.event;
|
||
// 僅當左鍵拖曳才阻止預設(避免影響下拉選單等)
|
||
if (e.button !== 0) return;
|
||
e.preventDefault();
|
||
// get the mouse cursor position at startup:
|
||
pos3 = e.clientX;
|
||
pos4 = e.clientY;
|
||
document.body.addEventListener("mouseup", closeDragElement, {
|
||
passive: false,
|
||
});
|
||
// call a function whenever the cursor moves:
|
||
document.body.addEventListener("mousemove", elementDrag, {
|
||
passive: false,
|
||
});
|
||
}
|
||
|
||
function elementDrag(e) {
|
||
e = e || window.event;
|
||
e.preventDefault();
|
||
// calculate the new cursor position:
|
||
pos1 = pos3 - e.clientX;
|
||
pos2 = pos4 - e.clientY;
|
||
pos3 = e.clientX;
|
||
pos4 = e.clientY;
|
||
// set the element's new position:
|
||
elmnt.style.top = elmnt.offsetTop - pos2 + "px";
|
||
elmnt.style.left = elmnt.offsetLeft - pos1 + "px";
|
||
}
|
||
|
||
function closeDragElement() {
|
||
// stop moving when mouse button is released:
|
||
document.body.removeEventListener("mouseup", closeDragElement);
|
||
document.body.removeEventListener("mousemove", elementDrag);
|
||
}
|
||
};
|
||
|
||
export const draggable = {
|
||
install(app) {
|
||
app.directive("draggable", {
|
||
mounted: (el, binding, vnode, prevVnode) => {
|
||
// console.log("draggable", $(`#${el.id}`).draggable);
|
||
if (binding.value) {
|
||
if ($(`#${el.id}`).draggable) {
|
||
$(`#${el.id}`).draggable({
|
||
cursor: "move",
|
||
scroll: true,
|
||
container: ".app-container",
|
||
});
|
||
} else {
|
||
moveModal(el);
|
||
}
|
||
}
|
||
},
|
||
});
|
||
},
|
||
};
|