萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 拖拽核心原理與排序拖拽實現詳解

一、基礎拖拽:三大事件模型

// 鼠標事件
element.onmousedown = startDrag;
document.onmousemove = dragging;
document.onmouseup = endDrag;

// 觸摸事件(移動端)
element.ontouchstart = startDrag;
document.ontouchmove = dragging;
document.ontouchend = endDrag;

為什麼綁定在 document 上?

若綁定在被拖拽元素上,鼠標移動過快會脫離元素範圍導致 mousemove 不觸發,拖拽中斷。document 覆蓋整個視口,保證捕獲全程移動。

核心邏輯

var Drag = {
    obj: null, // 當前拖拽元素

    init: function(o, oRoot, minX, maxX, minY, maxY) {
        o.onmousedown = Drag.start;
        o.root = oRoot || o; // 拖拽根元素(可為父容器)
        // 邊界限制配置...
    },

    start: function(e) {
        e = Drag.fixEvent(e);
        var o = Drag.obj = this;
        o.lastX = e.clientX;
        o.lastY = e.clientY;
        // 記錄初始位置
        o.startLeft = parseInt(o.root.style.left) || 0;
        o.startTop = parseInt(o.root.style.top) || 0;

        document.onmousemove = Drag.drag;
        document.onmouseup = Drag.end;
        return false; // 防止選中文本
    },

    drag: function(e) {
        e = Drag.fixEvent(e);
        var o = Drag.obj;
        var dx = e.clientX - o.lastX;
        var dy = e.clientY - o.lastY;
        // 邊界檢查...
        o.root.style.left = o.startLeft + dx + 'px';
        o.root.style.top = o.startTop + dy + 'px';
        return false;
    },

    end: function() {
        document.onmousemove = null;
        document.onmouseup = null;
        Drag.obj.root.onDragEnd?.();
        Drag.obj = null;
    },

    fixEvent: function(e) {
        e = e || window.event;
        // 兼容 layerX/Y
        if (e.layerX === undefined) e.layerX = e.offsetX;
        if (e.layerY === undefined) e.layerY = e.offsetY;
        return e;
    }
};

二、經典庫:dom-drag (Aaron Boodman) 源碼精華

支援水平/垂直模式切換、邊界限制、自定義映射函數、事件鉤子(onDragStart/onDrag/onDragEnd)。核心思想同上,但處理了 hmode/vmode(左右/上下定位模式)、minX/maxX 邊界轉換為鼠標座標限制、映射函數 xMapper/yMapper 實現非線性拖拽(如吸附網格)。

三、拖拽排序:列表項重排序

核心思路

  1. 按下:將被拖元素 position:absolute、創建佔位符 placeholder 插入原位置、記錄偏移。
  2. 移動:更新元素 left/top;遍歷其他列表項,若鼠標進入其區域(clientY 在元素中線上下),將 placeholder 移動到該元素前/後。
  3. 釋放:將真實元素移至 placeholder 位置、移除 placeholder、恢復 position:static。

冷月無聲版核心邏輯(簡化)

(function(win, doc) {
    var _this = null, info = {}, list = [];

    var Sortable = function(opts) {
        this.opts = opts;
        _this = this;
        list = getByClass(opts.sortClass, doc);
        addEvent(doc, 'mousedown', handleEvent);
        addEvent(doc, 'mousemove', handleEvent);
        addEvent(doc, 'mouseup', handleEvent);
    };

    Sortable.prototype = {
        handleEvent: function(e) {
            var target = e.target || e.srcElement;
            switch(e.type) {
                case 'mousedown':
                    if (hasClass(target, _this.opts.sortClass)) _this.downEvent(e, target);
                    break;
                case 'mousemove':
                    if (info.dObj) _this.moveEvent(e, target);
                    break;
                case 'mouseup':
                    if (info.dObj) _this.upEvent(e, target);
                    break;
            }
        },

        downEvent: function(e, target) {
            info.dObj = target; // 被拖元素
            var off = getOffset(target);
            target.x = e.clientX - off[0];
            target.y = e.clientY - off[1];
            target.style.position = 'absolute';
            target.style.left = off[0] + 'px';
            target.style.top = off[1] + 'px';

            info.vObj = doc.createElement('div'); // 佔位符
            info.vObj.style.width = off[2] + 'px';
            info.vObj.style.height = off[3] + 'px';
            target.parentNode.insertBefore(info.vObj, target);
        },

        moveEvent: function(e, target) {
            // 防止選中文本
            win.getSelection ? win.getSelection().removeAllRanges() : doc.selection.empty();

            // 移動實體元素
            info.dObj.style.left = e.clientX - info.dObj.x + 'px';
            info.dObj.style.top = e.clientY - info.dObj.y + 'px';

            // 遍歷列表項,判斷鼠標是否進入某項區域
            for (var i = 0; i < list.length; i++) {
                var item = list[i];
                if (item === info.dObj || item === info.vObj) continue;
                var off = getOffset(item);
                // 簡化:鼠標Y在項目中線以上→插入前面,以下→插入後面
                if (e.clientY < off[1] + off[3] / 2) {
                    item.parentNode.insertBefore(info.vObj, item);
                    break;
                } else if (i === list.length - 1) {
                    item.parentNode.insertBefore(info.vObj, item.nextSibling);
                }
            }
        },

        upEvent: function() {
            // 真實元素取代佔位符
            info.vObj.parentNode.insertBefore(info.dObj, info.vObj);
            info.vObj.parentNode.removeChild(info.vObj);
            info.dObj.style.position = '';
            info.dObj.style.left = '';
            info.dObj.style.top = '';
            info.dObj = info.vObj = null;
        }
    };

    // 工具函數:getByClass, addEvent, hasClass, getOffset 略
    // ...
})(window, document);

四、現代原生實現:HTML5 Drag & Drop API

<ul id="sortable">
  <li draggable="true">項目 1</li>
  <li draggable="true">項目 2</li>
  <li draggable="true">項目 3</li>
</ul>

<script>
var dragSrc = null;
var list = document.getElementById('sortable');

list.addEventListener('dragstart', function(e) {
    if (e.target.tagName === 'LI') {
        dragSrc = e.target;
        e.target.classList.add('dragging');
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/html', e.target.outerHTML);
    }
});

list.addEventListener('dragover', function(e) {
    e.preventDefault(); // 必須阻止默認才能 drop
    e.dataTransfer.dropEffect = 'move';
    var target = e.target;
    if (target.tagName === 'LI' && target !== dragSrc) {
        // 判斷插入位置
        var rect = target.getBoundingClientRect();
        var next = (e.clientY - rect.top) > (rect.height / 2);
        list.insertBefore(dragSrc, next ? target.nextSibling : target);
    }
});

list.addEventListener('dragend', function(e) {
    e.target.classList.remove('dragging');
    dragSrc = null;
});
</script>
  • 優點:原生、無需計算座標、支援跨窗口/應用拖拽、語義化。
  • 缺點:移動端不支援、樣式定制受限(拖拽幽靈圖像)、IE 支援不完整。

五、移動端觸摸拖拽

使用 touchstart/move/end,邏輯同鼠標,但需注意:

  • e.touches[0].clientX/Y 獲取座標。
  • 阻止默認滾動:e.preventDefault()(但會阻止頁面滾動,需權衡)。
  • iOS Safari 需 touch-action: none CSS 防止瀏覽器接管。

六、成熟庫推薦

  • SortableJS:原生、無依賴、支援觸摸、多列表、動畫、樹狀、虛擬列表,首選。
  • react-beautiful-dnd / dnd-kit:React 生態最佳。
  • Vue.Draggable:基於 SortableJS 的 Vue 封裝。

理解底層原理,選型與調試才能游刃有餘。

copyright © 萬盛學電腦網 all rights reserved