原生js實現【元素拖拽】so easy

 第一步:創建一個小盒子,絕對定位一下。

 <style>
        .box{
            position: absolute;
            left: 0;
            top: 0;
            width: 100px;
            height: 100px;
            background: red;
        }
     
</style>
<body>
<div class="box"></div>
</body>

第二步:實現思路:

實現思路:

1.獲取鼠標按下時的位置,獲取元素的初始位置

2.添加鼠標移動的事件監聽,獲取鼠標當前位置

3.計算鼠標移動距離

4.用鼠標移動距離+元素的初始位置 = 元素的當前位置

5.修改元素的位置,就跟着鼠標移動了!

6.當然到了這一步會發現,我們鬆開鼠標之後,小盒子還是跟着鼠標指針跑。因此這裏的關鍵步驟是取消事件監聽。

7.添加鼠標擡起事件,在鬆開鼠標之後,取消鼠標移動鼠標擡起的事件監聽~

第三步:開始敲代碼:(備註裏的數字對應第二步的實現思路的步驟)

<script>
    let box = document.querySelector(".box");//1.這裏獲取的是你要移動的元素
    let startMouse = {};
    let startPos = {};
    box.addEventListener("mousedown",function (e) {//2.添加鼠標按下事件監聽
        startMouse = {//鼠標初始位置
            x:e.clientX,
            y:e.clientY
        }
        startPos = {//元素初始位置
            x:box.getBoundingClientRect().left,
            y:box.getBoundingClientRect().top
        };
        e.preventDefault();
        document.addEventListener("mousemove",move);//添加鼠標移動事件監聽
        document.addEventListener("mouseup",up);//添加鼠標擡起事件監聽
    })

    function move(e) {
        let nowMouse = {//2.獲取鼠標移動時的當前位置
            x:e.clientX,
            y:e.clientY
        }
        let disMouse = {//3.計算鼠標移動距離
            x:nowMouse.x - startMouse.x,
            y:nowMouse.y - startMouse.y
        }
        let nowPosition = {//4.計算出元素應該在的位置
            x:startPos.x + disMouse.x,
            y:startPos.y + disMouse.y
        }
        box.style.left = nowPosition.x+"px";//5.修改元素位置
        box.style.top = nowPosition.y+"px";
    }
    function up() {//6.7.取消事件監聽
        document.removeEventListener("mousemove",move);
        document.removeEventListener("mouseup",up);
    }


</script>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章