Vue.js Draggable Directive: Move Elements with Ease
This is a Vue.js directive called 'draggable' that allows an element to be moved around the screen by clicking and dragging it.
The directive mounts on an element and sets its cursor to 'move' and its position to 'absolute'. When the element is clicked, it calculates the distance between the mouse pointer and the top-left corner of the element, and sets up a mousemove event listener that continuously updates the element's position based on the movement of the mouse pointer.
The directive also checks if the element is being dragged outside of its parent container and prevents it from going beyond the container's boundaries. When the mouse is released, the directive removes the event listeners to stop the dragging behavior.
This directive can be used in Vue.js templates by adding the 'v-draggable' attribute to an element, like so:
<template>
<div v-draggable>
<p>Drag me around!</p>
</div>
</template>
import type { Directive } from 'vue';
interface ElType extends HTMLElement {
parentNode: any;
}
const draggable: Directive = {
mounted: function (el: ElType) {
el.style.cursor = 'move';
el.style.position = 'absolute';
el.onmousedown = function (e) {
let disX = e.pageX - el.offsetLeft;
let disY = e.pageY - el.offsetTop;
document.onmousemove = function (e) {
let x = e.pageX - disX;
let y = e.pageY - disY;
let maxX = el.parentNode.offsetWidth - el.offsetWidth;
let maxY = el.parentNode.offsetHeight - el.offsetHeight;
if (x < 0) {
x = 0;
} else if (x > maxX) {
x = maxX;
}
if (y < 0) {
y = 0;
} else if (y > maxY) {
y = maxY;
}
el.style.left = x + 'px';
el.style.top = y + 'px';
};
document.onmouseup = function () {
document.onmousemove = document.onmouseup = null;
};
};
}
};
export default draggable;
原文地址: https://www.cveoy.top/t/topic/nNPp 著作权归作者所有。请勿转载和采集!