From the beginning of front-end development to the actual combat: to achieve the drag effect of a div

Posted by klainis on Mon, 04 Nov 2019 23:16:54 +0100

Implementation ideas:

  1. Mouse down to drag
  2. Record the mouse position and element position when pressing the mouse
  3. Drag the mouse to record the current mouse position
  4. Current mouse position - mouse position when pressing = mouse moving distance
  5. Element position = mouse moving distance + element position when the mouse is pressed

Code:

class Drag {
    //Constructor
    constructor(el) {
        this.el = el;
        //Element position when the mouse is pressed
        this.startOffset = {};
        //Mouse position when the mouse is pressed
        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);
        })
    }
    //Processing function when pressing
    start(e) {
        let { el } = this;
        this.startOffset = {
            x: el.offsetLeft,
            y: el.offsetTop
        }
        this.startPoint = {
            x: e.clientX,
            y: e.clientY
        }
    }
    //Processing function when mouse moves
    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);
})()

In order to help you make learning easier and more efficient, we will share a large number of materials for free, and help you to overcome difficulties on the way to becoming front-end engineers, or even full stack engineers. Here I would like to recommend a front-end full stack learning circle: 784783012, welcome to join the group for discussion, learning and communication, and common progress.
When we really start to learn, we inevitably don't know where to start, which leads to low efficiency and affects the confidence to continue learning.
But the most important thing is that we don't know which technology needs to be mastered. When we study, we often trample on the pit, and ultimately waste a lot of time, so effective resources are still necessary.