// 鼠標事件
element.onmousedown = startDrag;
document.onmousemove = dragging;
document.onmouseup = endDrag;
// 觸摸事件(移動端)
element.ontouchstart = startDrag;
document.ontouchmove = dragging;
document.ontouchend = endDrag;
若綁定在被拖拽元素上,鼠標移動過快會脫離元素範圍導致 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;
}
};
支援水平/垂直模式切換、邊界限制、自定義映射函數、事件鉤子(onDragStart/onDrag/onDragEnd)。核心思想同上,但處理了 hmode/vmode(左右/上下定位模式)、minX/maxX 邊界轉換為鼠標座標限制、映射函數 xMapper/yMapper 實現非線性拖拽(如吸附網格)。
position:absolute、創建佔位符 placeholder 插入原位置、記錄偏移。left/top;遍歷其他列表項,若鼠標進入其區域(clientY 在元素中線上下),將 placeholder 移動到該元素前/後。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);
<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>
使用 touchstart/move/end,邏輯同鼠標,但需注意:
e.touches[0].clientX/Y 獲取座標。e.preventDefault()(但會阻止頁面滾動,需權衡)。touch-action: none CSS 防止瀏覽器接管。理解底層原理,選型與調試才能游刃有餘。