实现一个div的拖拽效果

实现思路:

  1. 鼠标按下开始拖拽
  2. 记录摁下鼠标时的鼠标位置以及元素位置
  3. 拖动鼠标记下当前鼠标的位置
  4. 鼠标当前位置-摁下时鼠标位置= 鼠标移动距离
  5. 元素位置= 鼠标移动距离+鼠标摁下时元素的位置
            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);
            })()

     

 
posted @ 2019-04-12 16:55  yinping  阅读(3764)  评论(0编辑  收藏  举报