DIV CSS 佈局教程網

仿iGoogle首頁模組拖拽效果完整實現
編輯:關於JavaScript     

iGoogle 那種「首頁各模組可以自由拖動排序,且刷新後位置不變」的效果,本質上是三件事的組合:拖拽交互相對象、位置資料的序列化持久化、以及頁面載入時的位置還原。本文給出一份不依賴任何庫的完整實現。

整體結構

頁面由一個三欄 table 構成,每個 td 就是一個「欄位」,內部放若干 class 為 dragDiv 的模組區塊。每個模組有標題列(id 為 titleBarN)和內容區,標題列就是拖拽手柄。

程式碼分為 Common 工具集、Class 工廠、Drag 類三個部分,最後在 onload 中實例化、onunload 中保存配置。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS 仿 iGoogle 自定義首頁模塊拖拽效果</title>
<script type="text/javascript">
    var Common = {
        //ie/ff 事件物件獲取
        getEvent: function() {
             if (document.all) {
                 return window.event;
             }
             func = getEvent.caller;
             while (func != null) {
                 var arg0 = func.arguments[0];
                if (arg0) {
                      if ((arg0.constructor == Event || arg0.constructor == MouseEvent) ||
                          (typeof (arg0) == "object" && arg0.preventDefault && arg0.stopPropagation)) {
                          return arg0;
                      }
                 }
                func = func.caller;
             }
             return null;
        },
        //獲取滑鼠位置
        getMousePos: function(ev) {
             if (!ev) {
                 ev = this.getEvent();
             }
             if (ev.pageX || ev.pageY) {
                 return { x: ev.pageX, y: ev.pageY };
             }
             if (document.documentElement && document.documentElement.scrollTop) {
                 return {
                      x: ev.clientX + document.documentElement.scrollLeft - document.documentElement.clientLeft,
                      y: ev.clientY + document.documentElement.scrollTop  - document.documentElement.clientTop
                 };
             }
             else if (document.body) {
                 return {
                      x: ev.clientX + document.body.scrollLeft - document.body.clientLeft,
                      y: ev.clientY + document.body.scrollTop  - document.body.clientTop
                      };
             }
        },
        //獲取元素相對於文件的座標
        getElementPos: function(el) {
             el = this.getItself(el);
             var _x = 0, _y = 0;
             do {
                  _x += el.offsetLeft;
                 _y += el.offsetTop;
             } while (el = el.offsetParent);
             return { x: _x, y: _y };
        },
        getItself: function(id) {
             return "string" == typeof id ? document.getElementById(id) : id;
        },
        getViewportSize: {
             w: (window.innerWidth) ? window.innerWidth : (document.documentElement && document.documentElement.clientWidth) ? document.documentElement.clientWidth : (document.body ? document.body.offsetWidth : 0),
             h: (window.innerHeight) ? window.innerHeight : (document.documentElement && document.documentElement.clientHeight) ? document.documentElement.clientHeight : (document.body ? document.body.offsetHeight : 0)
        },
        isIE: document.all ? true : false,
        setOuterHtml: function(obj, html) {
             var Objrange = document.createRange();
             obj.innerHTML = html;
             Objrange.selectNodeContents(obj);
             var frag = Objrange.extractContents();
             obj.parentNode.insertBefore(frag, obj);
             obj.parentNode.removeChild(obj);
        },
        firstChild: function(parentObj, tagName) {
             if (Common.isIE) {
                 return parentObj.firstChild;
             }
             else {
                 var arr = parentObj.getElementsByTagName(tagName);
                 return arr[0];
             }
        },
        lastChild: function(parentObj, tagName) {
             if (Common.isIE) {
                 return parentObj.lastChild;
             }
             else {
                 var arr = parentObj.getElementsByTagName(tagName);
                 return arr[arr.length - 1];
             }
        },
        setCookie: function(name, value) {
             document.cookie = name + "=" + value;
        },
        getCookie: function(name) {
             var strCookie = document.cookie;
             var arrCookie = strCookie.split("; ");
             for (var i = 0; i < arrCookie.length; i++) {
                 var arr = arrCookie[i].split("=");
                 if (!arr[1]) {
                      return "";
                 }
                 if (arr[0] == name) {
                      return arr[1];
                 }
             }
             return "";
        },
        delCookie: function(name) {
             var exp = new Date();
             exp.setTime(exp.getTime() - 1);
             var cval = this.getCookie(name);
             if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
        }
    }

    //簡易的類工廠,構造時自動調用 init
    var Class = {
        create: function() {
             return function() { this.init.apply(this, arguments); }
        }
    }

    var Drag = Class.create();
    Drag.prototype = {
        init: function(titleBar, dragDiv, Options) {
             titleBar = Common.getItself(titleBar);
             dragDiv  = Common.getItself(dragDiv);
             this.dragArea = { maxLeft: -9999, maxRight: 9999, maxTop: -9999, maxBottom: 9999 };
             //設置點擊拖動時是否透明,預設透明 60%
             if (Options) {
                 this.opacity = Options.opacity ? (isNaN(parseInt(Options.opacity)) ? 100 : parseInt(Options.opacity)) : 100;
                 if (Options.area) {
                      if (Options.area.left   && !isNaN(parseInt(Options.area.left)))   { this.dragArea.maxLeft   = Options.area.left }
                      if (Options.area.right  && !isNaN(parseInt(Options.area.right))) { this.dragArea.maxRight  = Options.area.right }
                      if (Options.area.top    && !isNaN(parseInt(Options.area.top)))    { this.dragArea.maxTop    = Options.area.top }
                       if (Options.area.bottom && !isNaN(parseInt(Options.area.bottom))) { this.dragArea.maxBottom = Options.area.bottom };
                 }
             }
             else {
                  this.opacity = 60;
                 }
             this.originDragDiv = null;
             this.tmpX = 0;
             this.tmpY = 0;
             this.moveable = false;
             this.dragArray = [];

             var dragObj = this;
             var dragTbl = document.getElementById("dragTable");

             titleBar.onmousedown = function(e) {
                 var ev = e || window.event || Common.getEvent();
                 //只允許透過滑鼠左鍵拖拽,IE 左鍵為 1,Firefox 為 0
                 if (Common.isIE && ev.button == 1 || !Common.isIE && ev.button == 0) {
                 }
                 else {
                      return false;
                 }

                 //處理特殊情況:在最上/下面移動時不碰到現有 DIV 的情況下,又回到起始拖拽的列最上/下方
                 var tmpColId;
                 for (c = 0; c < dragTbl.rows[0].cells.length; c++) {
                      for (k = 0; k < dragTbl.rows[0].cells[c].getElementsByTagName("DIV").length; k++) {
                          if (dragDiv.id == dragTbl.rows[0].cells[c].getElementsByTagName("DIV")[k].id) {
                                tmpColId = c;
                                break;
                            }
                      }
                 }
                 var tmpPosFirstChild = Common.getElementPos(Common.firstChild(dragTbl.rows[0].cells[tmpColId], "DIV"));
                 var tmpPosLastChild  = Common.getElementPos(Common.lastChild(dragTbl.rows[0].cells[tmpColId], "DIV"));
                 var tmpObj = { colId: tmpColId, firstChildUp: tmpPosFirstChild.y, lastChildDown: tmpPosLastChild.y + Common.lastChild(dragTbl.rows[0].cells[tmpColId], "DIV").offsetHeight };

                 //保存當前可拖拽各容器的所在位置
                 dragObj.dragArray = dragObj.RegDragsPos();

                 //插入虛線框佔位
                 var dashedElement = document.createElement("div");
                 dashedElement.style.cssText = dragDiv.style.cssText;
                 dashedElement.style.border = " dashed 2px #aaa ";
                 dashedElement.style.marginBottom = "6px";
                 //減去 borderWidth 使虛線框大小與 dragDiv 保持一致
                 dashedElement.style.width  = dragDiv.offsetWidth  - 2 * parseInt(dashedElement.style.borderWidth) + "px";
                 //加上 px 保證 FF 正確
                 dashedElement.style.height = dragDiv.offsetHeight - 2 * parseInt(dashedElement.style.borderWidth) + "px";
                 dashedElement.style.position = "relative";
                 if (dragDiv.nextSibling) {
                      dragDiv.parentNode.insertBefore(dashedElement, dragDiv.nextSibling);
                 }
                 else {
                      dragDiv.parentNode.appendChild(dashedElement);
                 }
                 //拖動時改為 absolute 定位
                 dragDiv.style.width = dragDiv.offsetWidth + "px";
                 dragDiv.style.position = "absolute";

                 dragObj.moveable = true;
                 dragDiv.style.zIndex = dragObj.GetZindex() + 1;

                 var downPos = Common.getMousePos(ev);
                 dragObj.tmpX = downPos.x - dragDiv.offsetLeft;
                 dragObj.tmpY = downPos.y - dragDiv.offsetTop;

                 if (Common.isIE) {
                      dragDiv.setCapture();
                 } else {
                      window.captureEvents(Event.mousemove);
                 }

                 dragObj.SetOpacity(dragDiv, dragObj.opacity);

                 //FireFox 去除容器內拖拽圖片問題
                 if (ev.preventDefault) {
                      ev.preventDefault();
                      ev.stopPropagation();
                 }

                 document.onmousemove = function(e) {
                      if (dragObj.moveable) {
                          var ev = e || window.event || Common.getEvent();
                          //IE 去除容器內拖拽圖片問題
                          if (document.all) {
                               ev.returnValue = false;
                          }

                          var movePos = Common.getMousePos(ev);
                          dragDiv.style.left = Math.max(Math.min(movePos.x - dragObj.tmpX, dragObj.dragArea.maxRight), dragObj.dragArea.maxLeft) + "px";
                          dragDiv.style.top  = Math.max(Math.min(movePos.y - dragObj.tmpY, dragObj.dragArea.maxBottom), dragObj.dragArea.maxTop) + "px";

                          var targetDiv = null;
                          for (var k = 0; k < dragObj.dragArray.length; k++) {
                              if (dragDiv == document.getElementById(dragObj.dragArray[k].DragId)) {
                                   continue;
                                }

                                if (movePos.x > dragObj.dragArray[k].PosLeft && movePos.x < dragObj.dragArray[k].PosLeft + dragObj.dragArray[k].PosWidth
                                && movePos.y > dragObj.dragArray[k].PosTop  && movePos.y < dragObj.dragArray[k].PosTop + dragObj.dragArray[k].PosHeight
                                ) {
                                    targetDiv = document.getElementById(dragObj.dragArray[k].DragId);
                                    if (movePos.y < dragObj.dragArray[k].PosTop + dragObj.dragArray[k].PosHeight / 2) {
                                         //往上移
                                        dashedElement.style.width = targetDiv.offsetWidth - 2 * parseInt(dashedElement.style.borderWidth) + "px";
                                         targetDiv.parentNode.insertBefore(dashedElement, targetDiv);
                                    }
                                    else {
                                         //往下移
                                         dashedElement.style.width = targetDiv.offsetWidth - 2 * parseInt(dashedElement.style.borderWidth) + "px";
                                         if (targetDiv.nextSibling) {
                                             targetDiv.parentNode.insertBefore(dashedElement, targetDiv.nextSibling);
                                         }
                                         else {
                                         targetDiv.parentNode.appendChild(dashedElement);
                                    }
                                }
                             }
                            }

                             //判斷滑鼠是否落在某一欄內,處理跨欄與空欄的情形
                             for (j = 0; j < dragTbl.rows[0].cells.length; j++) {
                                var startLeft = Common.getElementPos(dragTbl.rows[0].cells[j]).x;
                                if (movePos.x > startLeft && movePos.x < startLeft + dragTbl.rows[0].cells[j].offsetWidth) {
                                    ///該列無 DIV
                                    if (dragTbl.rows[0].cells[j].getElementsByTagName("div").length == 0) {
                                        dashedElement.style.width = dragTbl.rows[0].cells[j].offsetWidth - 2 * parseInt(dashedElement.style.borderWidth) + "px";
                                        dragTbl.rows[0].cells[j].appendChild(dashedElement);
                                    }
                                else {
                                        var posFirstChild = Common.getElementPos(Common.firstChild(dragTbl.rows[0].cells[j], "DIV"));
                                        var posLastChild  = Common.getElementPos(Common.lastChild(dragTbl.rows[0].cells[j], "DIV"));
                                        //處理特殊情況:在最上/下面移動時不碰到現有 DIV 的情況下,又回到起始拖拽的列最上/下方
                                        var tmpUp, tmpDown;
                                        if (tmpObj.colId == j) {
                                            tmpUp   = tmpObj.firstChildUp;
                                         tmpDown = tmpObj.lastChildDown;
                                        }
                                        else {
                                            tmpUp   = posFirstChild.y;
                                        tmpDown = posLastChild.y + Common.lastChild(dragTbl.rows[0].cells[j], "DIV").offsetHeight;
                                        }

                                             if (movePos.y < tmpUp) { ///從最上面插入虛線框
                                             dashedElement.style.width = Common.firstChild(dragTbl.rows[0].cells[j], "DIV").offsetWidth - 2 * parseInt(dashedElement.style.borderWidth) + "px";
                                         dragTbl.rows[0].cells[j].insertBefore(dashedElement, Common.firstChild(dragTbl.rows[0].cells[j], "DIV"));
                                         }
                                         else if (movePos.y > tmpDown) { ///從最下面插入虛線框
                                        dashedElement.style.width = Common.lastChild(dragTbl.rows[0].cells[j], "DIV").offsetWidth - 2 * parseInt(dashedElement.style.borderWidth) + "px";
                                        dragTbl.rows[0].cells[j].appendChild(dashedElement);
                                         }

                                    }
                                }
                            }
                         }
                   };

                 document.onmouseup = function() {
                      if (dragObj.moveable) {
                          if (Common.isIE) {
                               dragDiv.releaseCapture();
                          }
                          else {
                               window.releaseEvents(Event.mousemove);
                          }
                          dragObj.SetOpacity(dragDiv, 100);
                          dragObj.moveable = false;
                          dragObj.tmpX = 0;
                          dragObj.tmpY = 0;

                          //務必寫在此 if 內
                          dragDiv.style.left = "";
                          dragDiv.style.top  = "";

                          dragDiv.style.width = "";
                          dragDiv.style.position = "";
                          //把元素插入虛線框所在位置,再移除虛線框,即完成排序
                          dashedElement.parentNode.insertBefore(dragDiv, dashedElement);
                          dashedElement.parentNode.removeChild(dashedElement);
                      }
                 };
             },
        SetOpacity: function(dragDiv, n) {
             if (Common.isIE) {
                 dragDiv.filters.alpha.opacity = n;
             }
             else {
                 dragDiv.style.opacity = n / 100;
             }
        },
        GetZindex: function() {
             var maxZindex = 0;
             var divs = document.getElementsByTagName("div");
             for (z = 0; z < divs.length; z++) {
                 maxZindex = Math.max(maxZindex, divs[z].style.zIndex);
             }
             return maxZindex;
        },
        //記錄所有可拖拽元素的目前位置與尺寸,供移動時做碰撞檢測
        RegDragsPos: function() {
             var arrDragDivs = new Array();
             var dragTbl = document.getElementById("dragTable");
             var tmpDiv, tmpPos;
             for (i = 0; i < dragTbl.getElementsByTagName("div").length; i++) {
                 tmpDiv = dragTbl.getElementsByTagName("div")[i];
                 if (tmpDiv.className == "dragDiv") {
                     tmpPos = Common.getElementPos(tmpDiv);
                     arrDragDivs.push({ DragId: tmpDiv.id, PosLeft: tmpPos.x, PosTop: tmpPos.y, PosWidth: tmpDiv.offsetWidth, PosHeight: tmpDiv.offsetHeight });
                 }
             }
             return arrDragDivs;
        }

    window.onload = function() {
        var dragTbl = document.getElementById("dragTable");
        //若有保存過的配置,先按配置還原各欄的模組順序
        if (Common.getCookie("configArr")) {
             var configArr = eval("(" + Common.getCookie("configArr") + ")");
             for (i = 0; i < dragTbl.rows[0].cells.length; i++) {
                 for (j = 0; j < configArr[i].length; j++) {
                     dragTbl.rows[0].cells[i].appendChild(document.getElementById(configArr[i][j]));
                 }
             }
        }
        new Drag("titleBar1", "dragDiv1");
        new Drag("titleBar2", "dragDiv2");
        new Drag("titleBar3", "dragDiv3");
        new Drag("titleBar4", "dragDiv4");
        new Drag("titleBar5", "dragDiv5");
    }

    //離開頁面前,把各欄目前的模組 id 順序存進 cookie
    window.onunload = function() {
        var dragTbl = document.getElementById("dragTable");
        var configArr = "";
        for (i = 0; i < dragTbl.rows[0].cells.length; i++) {
             var tmpStr = "";
             for (j = 0; j < dragTbl.rows[0].cells[i].getElementsByTagName("DIV").length; j++) {
                 tmpStr += (tmpStr == "" ? "" : ",") + "'" + dragTbl.rows[0].cells[i].getElementsByTagName("DIV")[j].id + "'";
             }
             configArr += (configArr == "" ? "" : ",") + "[" + tmpStr + "]";
             }
             //format like: [['dragDiv3','dragDiv5'],['dragDiv4','dragDiv1'],['dragDiv2']]
             Common.setCookie("configArr", "[" + configArr + "]");
    }
</script>
<style type="text/css">
    .dragDiv,.nodragDiv{
    position:relative;
    filter:alpha(opacity=100);
    opacity:1;
    margin-bottom:6px;
    background-color:#FFFFFF;
    }
</style>
</head>
<body>
    <table id="dragTable" cellpadding="3" style="border:solid 0px green;width:98%;">
        <tr>
            <td valign="top" style="width:30%">
                <div class="dragDiv" id="dragDiv1">
                    <table cellpadding="0" cellspacing="0" border="1" style="width:100%;border-collapse:collapse; border-color:Blue">
                        <tr id="titleBar1" style="height:22px; text-align:left; background-color:#547BC9;color:White; padding:3px;cursor:move;">
                            <th align="left" unselectable="on">Title1</th>
                        </tr>
                        <tr style="height:130px;padding:3px;" align="left" valign="top">
                            <td unselectable="on">這裡的字比較長....我來了....</td>
                        </tr>
                    </table>
                </div>
                <div class="dragDiv" id="dragDiv2">
                     <table cellpadding="0" cellspacing="0" border="1" style="width:100%;border-collapse:collapse; border-color:Blue">
                        <tr id="titleBar2" style="height:22px; text-align:left; background-color:#547BC9;color:White; padding:3px;cursor:move;">
                            <th align="left" unselectable="on">Title2</th>
                        </tr>
                        <tr style="height:130px;padding:3px;" align="left" valign="top">
                            <td unselectable="on">Content2...</td>
                        </tr>
                    </table>
                </div>
            </td>
            <td valign="top" style="width:50%">
                <div class="dragDiv" id="dragDiv3">
                    <table cellpadding="0" cellspacing="0" border="1" style="width:100%;border-collapse:collapse; border-color:Blue">
                        <tr id="titleBar3" style="height:22px; text-align:left; background-color:#547BC9;color:White; padding:3px;cursor:move;">
                            <th align="left" unselectable="on">Title3</th>
                        </tr>
                        <tr style="height:230px;padding:3px;" align="left" valign="top">
                            <td unselectable="on">Content3...</td>
                        </tr>
                        </table>
                </div>
            </td>
            <td valign="top" style="width:20%">
                <div class="dragDiv" id="dragDiv4">
                    <table cellpadding="0" cellspacing="0" border="1" style="width:100%;border-collapse:collapse; border-color:Blue">
                        <tr id="titleBar4" style="height:22px; text-align:left; background-color:#547BC9;color:White; padding:3px;cursor:move;">
                            <th align="left" unselectable="on">Title4</th>
                        </tr>
                        <tr style="height:130px;padding:3px;" align="left" valign="top">
                            <td unselectable="on">Content4...</td>
                        </tr>
                    </table>
                </div>
                <div class="dragDiv" id="dragDiv5">
                    <table cellpadding="0" cellspacing="0" border="1" style="width:100%;border-collapse:collapse; border-color:Blue">
                        <tr id="titleBar5" style="height:22px; text-align:left; background-color:#547BC9;color:White; padding:3px;cursor:move;">
                            <th align="left" unselectable="on">Title5</th>
                        </tr>
                        <tr style="height:130px;padding:3px;" align="left" valign="top">
                            <td unselectable="on">Content5...</td>
                        </tr>
                    </table>
                </div>
            </td>
        </tr>
    </table>
</body>
</html>

關鍵設計解析

整個效果的精髓在於「虛線框佔位」策略。拖拽開始時,程式碼做三件事:在原位置後插入一個尺寸相同的虛線 div;把被拖元素改為 absolute 定位並提升 z-index;同時降低透明度作為視覺回饋。拖動過程中,滑鼠只是帶著一個「浮起」的副本移動,真正決定順序的是那個虛線框——它根據滑鼠位置在各欄之間穿梭插入。滑鼠放開時,把被拖元素插到虛線框的位置,再刪除虛線框,排序就完成了。

這種做法避免了「拖動時元素佔位導致版面跳動」的經典難題,也讓插入位置的計算變得單純:只需要判斷滑鼠落在哪個元素的上半部還是下半部。

碰撞檢測依賴 RegDragsPos()。它在每次 mousedown 時快照所有 dragDiv 的位置與尺寸,形成 dragArray;mousemove 時逐一比對滑鼠座標是否落在某元素的矩形範圍內,並用「是否超過該元素高度的一半」來決定插到它前面還是後面。

程式碼中還專門處理了兩類邊界情況:一是拖到某欄的最上方或最下方、卻沒有碰到任何現有元素時,需要顯式判斷並插到首/尾;二是目標欄為空時,直接把虛線框 append 進去。這兩處若忽略,就會出現「拖到空白區域放手後元素彈回原位」的bug。

持久化部分很樸素:onunload 時遍歷每個 td 內的 div,把 id 順序拼成 `[['dragDiv3','dragDiv5'],['dragDiv4','dragDiv1'],['dragDiv2']]` 這樣的巢狀陣列字串存進 cookie;onload 時讀出來,按配置依序 appendChild 還原。注意 cookie 有 4KB 上限且會隨每次請求發送,模組數量多時應改用 localStorage,並用 JSON.stringify/JSON.parse 取代 eval 以避免安全風險。

如果今天重寫

HTML5 原生的拖放 API(draggable 屬性搭配 dragstart、dragover、drop 事件)能大幅簡化這套邏輯,無需手工計算座標;pointerdown 搭配 setPointerCapture 則能統一處理滑鼠與觸控。此外,鍵盤無障礙也不容忽視——應為每個模組的標題列加上「上移/下移」按鈕並提供 aria 標註,讓不使用滑鼠的人也能調整順序。原始碼中 collected 自網路的部分僅供學習交流,實際上線前建議重新梳理一遍邊界條件與事件清理邏輯。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved