萬盛學電腦網

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

JavaScript 仿 iGoogle 可拖曳模組化首頁佈局完整實作

功能需求

  • 多欄位佈局,每欄可容納多個模組區塊。
  • 模組標題列可拖曳,拖曳時顯示虛線佔位框。
  • 放入新欄位時,其他模組自動上下位移騰出空間。
  • 支援跨欄移動、同欄排序。
  • 可選:儲存排序狀態至 Cookie / LocalStorage。

核心架構

  1. Common 工具模組:事件標準化、滑鼠座標、元素座標、Viewport 尺寸、Cookie 操作等跨瀏覽器封裝。
  2. Class 簡易繼承:Class.create() 回傳建構函數,自動呼叫 init。
  3. Drag 類別:封裝拖曳邏輯(按下、移動、放開)、虛線框插入、碰撞檢測、欄位邊界限制。

關鍵程式碼片段

1. 滑鼠座標統一取得

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)
    };
}

2. 拖曳開始:建立虛線框、記錄初始位置、快取所有模組位置

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;
};

3. 拖曳中:移動實體元素、檢測進入哪個欄位、移動虛線框

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);
    }
};

4. 拖曳結束:替換虛線框為實體、儲存順序

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();
};

現代化替代方案

  • SortableJS:new Sortable(column, { group: 'shared', animation: 150 }) 幾行搞定多欄拖曳排序。
  • Vue Draggable / React Beautiful DnD:框架整合度高,支援虛擬列表、無障礙。
  • HTML5 Drag & Drop API:原生但 API 繁瑣,需處理 dragstart/dragover/drop 等事件,行動裝置支援需 Polyfill。

總結

iGoogle 風格拖曳佈局核心在於「虛線佔位框即時反饋」與「多欄碰撞檢測」。原始碼展示了早期跨瀏覽器 DHTML 的精髓;現代專案強烈建議使用成熟庫(SortableJS 等),專注業務邏輯而非底層事件處理。

copyright © 萬盛學電腦網 all rights reserved