Javascript之盒子拖拽(跟隨鼠標、邊界限定、軌跡回放)

本文通過拖拽案例,實現“跟隨鼠標、邊界限定、軌跡回放”三大效果;
完整代碼中有詳盡註釋,故不再進行細緻講解;
對於案例中需要注意的重點或易錯點問題,會總結在最後。

效果圖(僅演示左、上邊界限定)

盒子拖拽效果圖

完整代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>盒子拖拽</title>
    <style>
        body{
            margin: 0;
            padding: 0;
        }
        #box{
            width: 100px;
            height: 100px;
            background: skyblue;
            position: absolute;
            /* 盒子在頁面中的初始位置,可以隨意設置 */
            left: 200px; 
            top: 200px;
        }
        #btn{
            display: inline-block;
            width: 80px;
            height: 30px;
            font-size: 16px;
            cursor: pointer;
            outline: none;
        }
    </style>
</head>
<body>
    <div id="box"><button id="btn">軌跡回放</button></div>
    <script>
        var box_ele = document.getElementById("box");
        // 聲明位置數組,用於記錄盒子每次移動後的位置
        var position_arr = [];
        // 獲取頁面初始寬高,用於限定盒子移動邊界
        var screen_width = document.body.offsetWidth;
        var screen_height = window.innerHeight; // 注意頁面高度不能通過 document.body.offsetTop 獲取

        // 功能1:拖拽
        // 設置變量記錄鼠標的狀態,鼠標按下時爲true
        var flag = false;
        // 鼠標按下準備拖拽,記錄鼠標按下時的位置
        var mouse_x, mouse_y;
        box_ele.addEventListener("mousedown", function(evt){
            flag = true;
            var e = evt || event;
            mouse_x = e.offsetX; // 要以元素做參照物,用offset,不能用client
            mouse_y = e.offsetY;
            // 將盒子初始位置(盒子元素偏移量)記錄在位置數組中
            position_arr.push({
                x : box_ele.offsetLeft,
                y : box_ele.offsetTop
            })
        })
        // 鼠標移動拖拽開始
        // 事件綁定在document上,避免因鼠標移動速度太快超出盒子邊界時盒子跟不上
        document.addEventListener("mousemove", function(evt){
            if(flag){
                var e = evt || event;
                // 聲明盒子的位置
                var box_left = e.clientX - mouse_x;
                var box_top = e.clientY - mouse_y;
                // 通過頁面初始寬高和盒子寬高計算獲得盒子移動的最大值
                var move_width_max = screen_width - box_ele.offsetWidth;
                var move_height_max = screen_height - box_ele.offsetHeight;
                // 分別限定盒子移動的左右上下邊界
                box_left = box_left <= 0 ? 0 : box_left;
                box_left = box_left >= move_width_max ? move_width_max : box_left;
                box_top = box_top <= 0 ? 0 : box_top;
                box_top = box_top >= move_height_max ? move_height_max : box_top;
                // 將數據賦值給盒子從而在頁面中渲染
                box_ele.style.left = box_left + "px";
                box_ele.style.top = box_top + "px";
                // 若x或y方向移動距離大於5px,則將移動後的盒子位置記錄到位置數組中(避免數組中保存數據過多,消耗性能)
                if(box_left >= position_arr[position_arr.length - 1].x + 5 || box_top >= position_arr[position_arr.length - 1].y + 5){
                    position_arr.push({
                        x : box_left,
                        y : box_top
                    })
                }
                
            }
        })
        
        // 鼠標擡起拖拽停止
        box_ele.addEventListener("mouseup", function(){
            flag = false;
        })

        // 功能2:回放
        var btn_ele = document.getElementById("btn");
        var timer;
        btn_ele.addEventListener("click", function(){
            // 原思路:通過for循環遍歷位置數組中的每一個位置
            // 由於for循環執行太快,故使用定時器
            timer = setInterval(function(){
                // 每次取出位置數組中的最後一個元素位置
                var last_position = position_arr.pop();
                box_ele.style.left = last_position.x + "px";
                box_ele.style.top = last_position.y + "px";
                // 當移動到最後一個位置(即位置數組中數據爲空)時,關閉定時器
                if(position_arr.length === 0){
                    clearInterval(timer);
                }
            }, 50)
        })
    </script>
</body>
</html>

注意點

1、鼠標拖拽過程中的盒子位置需要通過 鼠標位置 - 初始時鼠標相對於元素位置 獲取,即
box_left = e.clientX - mouse_x
box_top = e.clientY - mouse_y;
否則盒子會出現在鼠標的右下方。

2、初始的頁面高度不能通過 document.body.offsetTop 獲取,需要用 window.innerHeight

3、限制鼠標移動邊界時,寬高方向的最大值需要通過 初始頁面寬高 - 盒子寬高 獲取,即
move_width_max = screen_width - box_ele.offsetWidth;
move_height_max = screen_height - box_ele.offsetHeight;

4、軌跡回放時,目標是位置數組中從後往前依次取出元素,最好的辦法就是使用 pop()

5、注意定時器的關閉條件。position_arr.length === 0

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