Realization of ideas:
- Start dragging the mouse down
- Mouse position and press the recording element of the mouse position
- Drag the mouse note of the current position of the mouse
- Current mouse position - pressed the mouse when the mouse position movement distance =
- Element position = position + mouse movement distance elements when pressed the mouse
Code:
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);
})()
One learns there will be confusion, lack of motivation. Here's what I recommend front-end learning exchange group: 731 771 211, which is the front end of the study, if you want to create web pages cool, want to learn programming. Himself compiled a front-end 2019 the most comprehensive study materials, from the most basic HTML + CSS + JS [cool special effects, games, plug-in package design patterns] to move to the end of the project HTML5 real learning materials are finishing, gave every front-end junior partner, had wanted to learn web front-end, or change jobs, or college students, as well as work want to upgrade their skills, are welcome to join the junior partner to learn to learn.
Click: join