Class.create() 回傳建構函數,自動呼叫 init。getMousePos: function(ev) {
ev = ev || this.getEvent();
if (ev.pageX != null) return { x: ev.pageX, y: ev.pageY };
const doc = document.documentElement;
const body = document.body;
return {
x: ev.clientX + (doc.scrollLeft || body.scrollLeft) - (doc.clientLeft || 0),
y: ev.clientY + (doc.scrollTop || body.scrollTop) - (doc.clientTop || 0)
};
}
titleBar.onmousedown = function(e) {
// 僅左鍵
if (Common.isIE && e.button !== 1 || !Common.isIE && e.button !== 0) return;
// 快取各欄現有模組位置,供碰撞檢測
dragObj.dragArray = dragObj.RegDragsPos();
// 建立虛線佔位框
const dashed = document.createElement('div');
dashed.style.cssText = dragDiv.style.cssText;
dashed.style.border = 'dashed 2px #aaa';
dashed.style.marginBottom = '6px';
// 插入到被拖曳元素前
dragDiv.parentNode.insertBefore(dashed, dragDiv);
dragObj.originDragDiv = dragDiv;
dragObj.tmpX = mouse.x - dragDiv.offsetLeft;
dragObj.tmpY = mouse.y - dragDiv.offsetTop;
dragObj.moveable = true;
};
document.onmousemove = function(e) {
if (!dragObj.moveable) return;
const mouse = Common.getMousePos(e);
// 移動實體元素(absolute 定位)
dragObj.originDragDiv.style.left = mouse.x - dragObj.tmpX + 'px';
dragObj.originDragDiv.style.top = mouse.y - dragObj.tmpY + 'px';
// 檢測滑鼠進入哪個欄位
const col = dragObj.getTargetColumn(mouse);
if (col !== null) {
// 在該欄內找到虛線框應插入的位置(根據 Y 軸)
const insertBefore = dragObj.getInsertPosition(col, mouse.y);
col.insertBefore(dashed, insertBefore);
}
};
document.onmouseup = function() {
if (!dragObj.moveable) return;
dragObj.moveable = false;
// 將虛線框替換回原始元素
const dashed = document.querySelector('.dashed-placeholder');
if (dashed) {
dashed.parentNode.replaceChild(dragObj.originDragDiv, dashed);
}
// 可選:儲存新順序
// saveLayout();
};
new Sortable(column, { group: 'shared', animation: 150 }) 幾行搞定多欄拖曳排序。dragstart/dragover/drop 等事件,行動裝置支援需 Polyfill。iGoogle 風格拖曳佈局核心在於「虛線佔位框即時反饋」與「多欄碰撞檢測」。原始碼展示了早期跨瀏覽器 DHTML 的精髓;現代專案強烈建議使用成熟庫(SortableJS 等),專注業務邏輯而非底層事件處理。