實現一個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);
            })()

     

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM