实现一个div的拖拽效果
发布时间:2020-01-06 03:43

mg游戏中心,实现思路:

鼠标按下开始拖拽记录摁下鼠标时的鼠标位置以及元素位置拖动鼠标记下当前鼠标的位置鼠标当前位置-摁下时鼠标位置= 鼠标移动距离元素位置= 鼠标移动距离+鼠标摁下时元素的位置代码:

class Drag { //构造函数 constructor(el) { this.el = el; //鼠标摁下时的元素位置 this.startOffset = {}; //鼠标摁下时的鼠标位置 this.startPoint = {}; let move = (e) = { this.move(e); }; let end = (e) = { document.removeEventListener("mousemove", move); document.removeEventListener("mouseup", end); }; el.addEventListener("mousedown", (e) = { this.start(e); document.addEventListener("mousemove", move); document.addEventListener("mouseup", end); }) } //摁下时的处理函数 start(e) { let { el } = this; this.startOffset = { x: el.offsetLeft, y: el.offsetTop } this.startPoint = { x: e.clientX, y: e.clientY } } //鼠标移动时的处理函数 move(e) { let { el, startOffset, startPoint } = this; let newPoint = { x: e.clientX, y: e.clientY } let dis = { x: newPoint.x - startPoint.x, y: newPoint.y - startPoint.y, } el.style.left = dis.x + startOffset.x + "px"; el.style.top = dis.y + startOffset.y + "px"; }}(function () { let box = document.querySelector("#box"); let dragbox = new Drag(box);})()
下一篇:没有了