DIV CSS 佈局教程網

自製可打字搜尋的 Ajax 下拉框 GooCombo 元件設計解析
編輯:JQuery入門技巧     

原生 <select> 在選項破百之後幾乎不能用,使用者得滑到手軟。本文示範如何打造一個「可以打字過濾、可選、可遠端載入」的下拉框元件 GooCombo,並把它掛進 jQuery 物件體系,讓呼叫方式與原生 API 一致。

一、通用工具函式(GooFunc.js)

元件需要幾個與瀏覽器相容性有關的小工具,先準備好:

// 取得元素絕對座標(即使不是絕對定位也能算)
function getElCoordinate(dom) {
    var t = dom.offsetTop;
    var l = dom.offsetLeft;
    dom = dom.offsetParent;
    while (dom) {
        t += dom.offsetTop;
        l += dom.offsetLeft;
        dom = dom.offsetParent;
    }
    return { top: t, left: l };
}

// 相容各瀏覽器取得滑鼠真實位置
function mousePosition(ev) {
    if (!ev) ev = window.event;
    if (ev.pageX || ev.pageY) {
        return { x: ev.pageX, y: ev.pageY };
    }
    return {
        x: ev.clientX + document.documentElement.scrollLeft - document.body.clientLeft,
        y: ev.clientY + document.documentElement.scrollTop  - document.body.clientTop
    };
}

// 為 Date 擴充格式化輸出
Date.prototype.format = function(format) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S":  this.getMilliseconds()
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1,
            (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1,
                RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

二、GooCombo 建構子(GooCombo.js)

這個元件接受兩種輸入:直接丟一個既有 <select>,或丟一個空 div 由元件自行產生 select。前者適合改造舊頁面,後者適合全新開發。

1. 屬性宣告與參數設定

/* 下拉框定義 —— GooCombo 類 */
// dom      : 要綁定的 DOM,需具備 id 或 name
// property : JSON 參數
function GooCombo(dom, property) {
    this.$div  = null;   // 渲染完成後最外層 div
    this.$id   = null;   // select 的 id
    this.$name = null;   // select 的 name
    this.$width = property.width;                       // 必填:寬度
    this.$haveIcon = property.haveIcon || false;

    // 永遠顯示的 text input
    this.$input = $("<input type='text' value='" + property.text + "' "
        + (property.readOnly ? "readonly='readonly'" : "") + "/>");

    this.$btn  = $("<div class='btn_up'</div>");       // 右側按鈕
    this.$data = [];                                    // 二維資料 [值, 文字, 圖示]
    this.$type = "basic";        // basic / multiple / filter 三種模式
    this.$selectHeight = property.selectHeight || 0;
    this.$list = $("<ul></ul>");                     // 下拉列表
    this.$lastSelect = null;     // 最近一次選中項
    this.$select = null;         // 隱藏的 select,用來存值
    this.$autoLoad   = false;    // 是否延遲載入
    this.$alreadyLoad = false;   // 是否已載入過

    // 延遲載入:focus 時才取資料
    this.setAutoLoad = function(bool) { this.$autoLoad = true; };
    if (property.autoLoad) this.setAutoLoad(property.autoLoad);

    // 遠端資料來源設定
    this.$ajaxType = null;
    this.setAjaxType = function(json) {
        this.$ajaxType.url      = json.url;
        this.$ajaxType.type     = json.type;
        this.$ajaxType.para     = json.para;
        this.$ajaxType.dataType = json.dataType;
    };
    if (property.ajaxType) this.setAjaxType(property.ajaxType);

2. 建構主體:接管既有 select 或自建容器

    if (dom != null && dom.tagName == "SELECT") {
        var temp = "";
        for (var i = 0; i < dom.length; i++) {
            this.$data[i] = [(dom.options[i].value || dom.options[i].text),
                              dom.options[i].text, ""];
            temp += "<a href='#'><p value='" + this.$data[i][0] + "'>"
                  + this.$data[i][1] + "</p></a>";
        }
        this.$list.append(temp);
        this.$id   = dom.id;
        this.$name = dom.name;
        if (dom.multiple) this.$type = "multiple";
        this.$select = $(dom);
        this.$select.wrap("<div class='Combo' id='Combo_" + this.$id + "'></div>");
        this.$div = this.$select.parent(".Combo");
    } else {
        this.$div = $(dom);
        this.$div.addClass("Combo");
        this.$select = $("<select></select>");
        this.$div.append(this.$select);
    }

    this.$div.css({ width: this.$width + "px" });
    this.$div.append("<div class='text'></div>").append(this.$btn).append(this.$list);
    this.$div.children("div:eq(0)")
             .append("<div class='top_border'</div>")
             .append(this.$input);

    // property 可覆寫原 select 的 id / name / type
    if (property.id)   { this.$id = property.id;   this.$select.attr("id", property.id); }
    if (property.name) { this.$name = property.name; this.$select.attr("name", property.name); }
    if (property.type) {
        this.$type = property.type;
        if (property.type == "multiple") {
            this.$select.attr("size", 1).attr("multiple", property.type);
        } else {
            this.$select.removeAttr("multiple");
        }
    }

3. 資料載入與遠端請求

    // 載入一組資料
    this.loadListData = function(data) {
        this.$data = [];
        if (this.$list.children("a").length > 0) {
            this.$list.empty();
            this.$select.empty();
        }
        var temp = "", temp2 = "";
        for (var i = 0; i < data.length; ++i) {
            this.$data[i] = [data[i][0], data[i][1], data[i][2] || ""];
            temp  += "<a href='#'><p value='" + this.$data[i][0] + "'>"
                   + this.$data[i][1] + "</p></a>";
            temp2 += "<option value='" + this.$data[i][0] + "'>"
                   + this.$data[i][1] + "</option>";
        }
        this.$list.append(temp);
        this.$select.append(temp2);
        this.$alreadyLoad = true;
    };
    if (property.data) this.loadListData(property.data);

    // 遠端載入
    this.loadListDataAjax = function() {
        var inthis = this;
        $.ajax({
            type     : this.$ajaxType.type,
            url      : this.$ajaxType.url,
            dataType : this.$ajaxType.dataType,
            data     : this.$ajaxType.para,
            success  : function(data) { inthis.loadListData(data); }
        });
    };

4. 事件綁定

focus 時負責「顯示列表 + 綁定點擊外部關閉」,是整個元件互動的入口:

    this.$input.bind("focus", { inthis: this }, function(e) {
        if (e && e.preventDefault) e.preventDefault();
        else window.event.returnValue = false;

        var inthis = e.data.inthis;

        // 尚未載入且啟用延遲載入時才發請求
        if (!inthis.$alreadyLoad && inthis.$autoLoad) {
            if (inthis.$ajaxType) { inthis.loadListDataAjax(); }
            else                  { inthis.loadListData(inthis.$data); }
        }

        var list = inthis.$list;
        list.css("display", "block");

        // 點擊列表以外的地方就收起
        $(document).bind("mouseup", function(e) {
            var locate = getElCoordinate(list.get(0));
            var ev = mousePosition(e);
            if (locate.left + inthis.$width < ev.x || locate.left > ev.x
                || locate.top - 22 > ev.y || locate.top + inthis.$selectHeight + 2 < ev.y) {
                list.css("display", "none");
            }
            this.onmouseup = null;
            return false;
        });
        return false;
    });

filter 模式下,input 內容變動就重新過濾:

    if (this.$type == "filter") {
        this.$input.bind("change", { inthis: this }, function(e) {
            var inthis = e.data.inthis;
            var text = $.trim(this.value);
            var data = inthis.$data;
            var temp = "";

            if (inthis.$ajaxType) {
                // 有遠端來源就把 keyword 當成 search 參數送回去,由後端做前置模糊比對
                inthis.$ajaxType.para["search"] = text;
                inthis.loadListDataAjax();
            } else {
                for (var i = 0; i < data.length; ++i) {
                    if (data[i][1].indexOf(text) == 0) {
                        temp += "<a href='#'><p value='" + data[i][0] + "'>"
                              + data[i][1] + "</p></a>";
                    }
                }
                inthis.$list.empty().append(temp);
            }
        });
    }

鍵盤操作:Enter 收起、方向鍵上下移動、其餘按鍵延遲觸發 change 以實現打字搜尋:

    this.$input.bind("keyup", { input: this.$input, list: this.$list }, function(e) {
        if (!e) e = window.event;
        if (e.keyCode == 13) {
            e.data.list.css("display", "none");
        } else if (e.keyCode == 40) {
            var temp = e.data.list.children("a:eq(0)");
            temp.focus().toggleClass("focus");
        } else {
            once = setTimeout(function() { e.data.input.change(); }, 500);
        }
    });

列表項點擊後,把值寫進隱藏 select 並觸發 change,讓原本的表單邏輯完全不用改:

    this.$list.bind("click", { inthis: this }, function(e) {
        if (e && e.preventDefault) e.preventDefault();
        else window.event.returnValue = false;

        var clicked = $(e.target);
        var inthis  = e.data.inthis;
        if (clicked.attr("tagName") == "A")      clicked = clicked.children("p");
        else if (clicked.attr("tagName") == "UL") { this.style.display = "none"; return; }

        if (inthis.$type != "multiple") {
            if (inthis.$lastSelect) inthis.$lastSelect.removeClass("active");
            inthis.$lastSelect = clicked.parent("a").addClass("active");
            this.style.display = "none";
            inthis.$select.val(clicked.attr("value"));
            inthis.$input.val(clicked.text());
        } else {
            clicked.parent("a").toggleClass("active");
            var optionList = inthis.$select.get(0).options;
            for (var i = 0; i < optionList.length; ++i) {
                if (optionList[i].value == clicked.attr("value")) {
                    optionList[i].selected = !optionList[i].selected;
                    break;
                }
            }
        }
        inthis.$select.change();
        return false;
    });

5. 對外 API

    // 取得選中值
    this.getValue = function() { return this.$select.val(); };

    // 綁定值變動,可實作下拉框聯動
    this.bindValueChange = function(Fn) { this.$select.bind("change", Fn); };

    // 刪除 / 新增 / 清空選項
    this.delItem = function(index) {
        this.$data.splice(index, 1);
        this.$select.get(0).options.remove(index);
        this.$list.children("a:eq(" + index + ")").remove();
    };
    this.clearItems = function() {
        this.$data = [];
        this.$list.empty();
        this.$select.get(0).options.length = 0;
        this.$alreadyLoad = false;
    };
}

// 掛進 jQuery,呼叫方式與原生 API 一致
jQuery.extend({
    createGooCombo: function(dom, property) {
        return new GooCombo(dom, property);
    }
});

三、頁面使用方式

先引入 jQuery,再建立元件:

$(document).ready(function () {
    var property = {
        id: "demo",
        name: "demo",
        type: "filter",          // 可打字過濾
        readOnly: false,
        width: 160,
        selectHeight: 140,
        autoLoad: true,
        haveIcon: false,
        text: "可輸入員工姓名查找"
    };
    var combo = $.createGooCombo(document.getElementById("combo"), property);
    combo.loadListData(datas);
});

四、後端產生二維陣列 JSON

元件吃的是 [值, 顯示文字, 圖示樣式] 的二維陣列,用 ashx 一般處理常式從 DataTable 轉出即可:

public string CreateJsonParameters(DataTable dt)
{
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    if (dt != null)
    {
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            sb.Append("[")
              .Append(dt.Rows[i]["EmployeeID"].ToString()).Append(", ")
              .Append(dt.Rows[i]["EmployeeNameID"].ToString())
              .Append("],");
        }
    }
    return sb.ToString().TrimEnd(',');
}
// 前端以 var datas = [<%=jsonString%>]; 接收

設計重點回顧

  • 保留原生 select:元件始終維護一個隱藏 select,因此表單提交、表單驗證、後端取值完全沿用舊邏輯,遷移成本極低。
  • 三種模式分工:basic 只選、multiple 多選、filter 打字過濾,用一個 $type 切換,避免寫三份相似程式碼。
  • 本地與遠端雙軌:filter 模式下若有 ajaxType,每次 change 都把 keyword 當 search 參數送回後端做前置模糊查詢,適合萬筆級資料;否則在前端以 indexOf 過濾。
  • 點擊外部關閉:靠 getElCoordinate 取絕對座標,再比對滑鼠位置是否落在列表範圍內,這也是為什麼需要那兩個工具函式。

以上就是 GooCombo 可輸入文字查詢下拉框的完整實作說明,需要的朋友可以依自身樣式與資料格式再作調整。

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