DIV CSS 佈局教程網

ScrollableGridPlugin.js 固定表頭插件源碼逐行解析
編輯:JQuery特效代碼     

ScrollableGridPlugin.js 是網上流傳很廣的一個小插件,專門替 ASP.NET GridView 加上「表頭固定、內容可捲動」的效果。它使用起來非常省事,視覺效果也不錯;但畢竟不是為你的專案量身訂做的,用在實戰前多少要改一點。想改得對,就得先讀懂作者的思路。

完整源碼與逐行註解

/*!
 * This plug-in is developed for ASP.Net GridView control
 * to make the GridView scrollable with Fixed headers.
 */
(function ($) {
    $.fn.Scrollable = function (options) {
        // 1、定義 jQuery 實例方法,這是我們呼叫插件的入口
        var defaults = { ScrollHeight: 300, Width: 0 };
        // 2、擴充設定:外部沒傳 ScrollHeight 就用預設 300
        var options = $.extend(defaults, options);

        return this.each(function () {
            var grid = $(this).get(0);              // 3、取得當前 GridView 的原生物件
            var gridWidth = grid.offsetWidth;       // 4、取得 GridView 寬度
            var headerCellWidths = new Array();

            // 5、建立陣列,存放表頭各欄的寬度
            for (var i = 0; i < grid.getElementsByTagName("TH").length; i++) {
                headerCellWidths[i] = grid.getElementsByTagName("TH")[i].offsetWidth;
            }

            grid.parentNode.appendChild(document.createElement("div")); // 6、在 GridView 同層最後補一個 div
            var parentDiv = grid.parentNode;                            // 7、GridView 的父節點

            var table = document.createElement("table");                // 8、建立一個新的 table
            // 9、把 GridView 的屬性(id 除外)全部搬到新 table 上
            for (i = 0; i < grid.attributes.length; i++) {
                if (grid.attributes[i].specified && grid.attributes[i].name != "id") {
                    table.setAttribute(grid.attributes[i].name, grid.attributes[i].value);
                }
            }
            table.style.cssText = grid.style.cssText;                   // 10、樣式也搬過去
            table.style.width = gridWidth + "px";                       // 11、寬度與原 GridView 一致
            table.appendChild(document.createElement("tbody"));         // 12、補一個 tbody

            // 13、把 GridView 的第一列(表頭)搬進新 table
            table.getElementsByTagName("tbody")[0].appendChild(grid.getElementsByTagName("TR")[0]);

            var cells = table.getElementsByTagName("TH");               // 14、新 table 的標題格集合
            var gridRow = grid.getElementsByTagName("TR")[0];           // 15、搬走表頭後,GridVie
w 剩下的第一列就是資料列

            // 16~17、表頭與資料格取較寬者,統一欄寬
            for (var i = 0; i < cells.length; i++) {
                var width;
                if (headerCellWidths[i] > gridRow.getElementsByTagName("TD")[i].offsetWidth) {
                    width = headerCellWidths[i];
                } else {
                    width = gridRow.getElementsByTagName("TD")[i].offsetWidth;
                }
                // 18、統一欄寬,-3 是為了微調表格樣式,並非必要
                cells[i].style.width = parseInt(width - 3) + "px";
                gridRow.getElementsByTagName("TD")[i].style.width = parseInt(width - 3) + "px";
            }

            parentDiv.removeChild(grid);   // 19、把 GridView 從文件流中移除(實際仍在記憶體裡)

            var dummyHeader = document.createElement("div");  // 20、再建一個 div
            dummyHeader.appendChild(table);                   // 21、把只含表頭的 table 放進去
            parentDiv.appendChild(dummyHeader);               // 22、插回原本 GridView 的位置

            if (options.Width > 0) { gridWidth = options.Width; }  // 23、若外部指定寬度就採用

            var scrollableDiv = document.createElement("div");    // 24、再建一個 div
            gridWidth = parseInt(gridWidth) + 17;                 // 25、+17 是留給捲軸的寬度
            scrollableDiv.style.cssText = "overflow:auto;height:" + options.ScrollHeight + "px;width:" + gridWidth + "px"; // 26
            scrollableDiv.appendChild(grid);                      // 27、把只剩資料列的 GridView 放進來
            parentDiv.appendChild(scrollableDiv);                 // 28、掛到表頭下方
        });
    };
})(jQuery);

整個思路就是「一分為二」

作者的核心手法很單純:把原本一張表拆成兩個 table。上面那個只裝表頭,不滾動;下面那個裝資料,外面包一層 overflow:auto 的 div 負責捲動。兩個 table 的欄寬必須一致,所以第 16~18 行才要逐一比對並統一。而 gridWidth + 17 是為了補上捲軸佔掉的寬度,否則資料列表頭會對不齊;這個 17 依平台而異,實測微調即可。

一個值得注意的細節

第 13 行和第 15 行都寫了 grid.getElementsByTagName("TR")[0],表面上看應該抓到同一列,但實際上第 13 行抓到的是含 TH 的表頭列,第 15 行抓到的卻是含 TD 的第一筆資料列。

原因在於第 13 行執行完之後,GridView 裡的 TR 數量少了一。也就是說,appendChild 是「搬移」節點,而不是「複製」節點——被 append 的元素會從原本的父節點被移走。所以第 15 行再取 [0] 時,索引 0 已經指向原本的資料列了。文件裡對這點寫得不明確,直接中招的人不少,這裡特別標出來。

怎麼呼叫

<script type="text/javascript" src="../Scripts/PlugIn/ScrollableGridPlugin.js"></script>
<script type="text/javascript">
jQuery(document).ready(function () {
    jQuery("#<%=gv_bugList.ClientID %>").Scrollable({ ScrollHeight: 400, Width: 500 });
});
</script>

把 GridView 的 ClientID 當成選擇器傳進去,設定捲動區高度與表格寬度就完成了。理解插件內部怎麼運作之後,要調整成符合自己專案的樣子(例如支援固定多列表頭、或改用 CSS class 控制寬度)就不再困難。

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