DIV CSS 佈局教程網

jQuery 郵箱輸入自動補全下拉提示外掛實作
編輯:關於JavaScript     

由於郵箱註冊幾乎免費,多數網站乾脆直接用信箱當帳號。為了讓使用者少打幾個字、少出錯,輸入 @ 之後自動補全省事網域就成了標配功能。本文把這個判斷得很完整的 jQuery 外掛整理出來,方便日後查閱。

功能重點

外掛會在使用者輸入時比對常見網域清單,把符合的項目列出;@ 前的部分會高亮標示,可用上下鍵切換候選、Enter 確認,滑鼠移入也能切換並點選填入。此外還支援「提示文字自動隱藏」的 placeholder 模擬效果。

HTML 結構

<div class="reg_lin1">
  <div class="lin1_1">常用郵箱:</div>
  <div class="lin1_2"><input type="text" class="reg_text" id="email" name="email" /></div>
  <div class="lin1_3"></div>
</div>

CSS:四個 class 分別對應四種狀態

.out_box{border:1px solid #ccc;background:#fff;font:12px/20px Tahoma;}
.list_box{border-bottom:1px solid #eee;padding:0 5px;cursor:pointer;}
.focus_box{background:#f0f3f9;}
.mark_box{color:#c00;}

外掛主體

(function ($) {
    $.fn.mailAutoComplete = function (options) {
        var defaults = {
            boxClass: "mailListBox",     // 外部 box 樣式
            listClass: "mailListDefault",// 預設列表樣式
            focusClass: "mailListFocus", // 列表選中樣式
            markCalss: "mailListHlignt", // 高亮樣式
            zIndex: 1,
            autoClass: true,             // 是否使用外掛自帶樣式
            mailArr: ["qq.com", "gmail.com", "126.com", "163.com", "hotmail.com",
                      "yahoo.com", "yahoo.com.cn", "live.com", "sohu.com", "sina.com"],
            textHint: false,             // 文字提示自動顯示與隱藏
            hintText: "",
            focusColor: "#333",
            blurColor: "#999"
        };
        var settings = $.extend({}, defaults, options || {});

        // 若未指定自訂樣式,動態注入一份預設 CSS
        if (settings.autoClass && $("#mailListAppendCss").size() === 0) {
            $('<style id="mailListAppendCss" type="text/css">' +
              '.mailListBox{border:1px solid #369;background:#fff;font:12px/20px Arial;}' +
              '.mailListDefault{padding:0 5px;cursor:pointer;white-space:nowrap;}' +
              '.mailListFocus{padding:0 5px;cursor:pointer;white-space:nowrap;background:#369;color:white;}' +
              '.mailListHlignt{color:red;}' +
              '.mailListFocus .mailListHlignt{color:#fff;}</style>').appendTo($("head"));
        }

        var cb = settings.boxClass, cl = settings.listClass,
            cf = settings.focusClass, cm = settings.markCalss;
        var z = settings.zIndex, newArr = mailArr = settings.mailArr,
            hint = settings.textHint, text = settings.hintText,
            fc = settings.focusColor, bc = settings.blurColor;

        // 產生候選列表 HTML,cur 為目前選中項
        $.createHtml = function (str, arr, cur) {
            var mailHtml = "";
            if ($.isArray(arr)) {
                $.each(arr, function (i, n) {
                    mailHtml += '<div class="mailHover ' + (i === cur ? cf : cl) +
                        '" id="mailList_' + i + '"><span class="' + cm + '">' +
                        str + '</span>@' + arr[i] + '</div>';
                });
            }
            return mailHtml;
        };

        var index = -1, s;
        $(this).each(function () {
            var that = $(this), i = $(".justForJs").size();
            if (i > 0) { return; } // 只綁定一個輸入框

            var w = that.outerWidth(), h = that.outerHeight();
            // 用 span 包住輸入框作為定位參照,並在其後插入候選層
            that.wrap('<span style="display:inline-block;position:relative;"></span>')
               .before('<div id="mailListBox_' + i + '" class="justForJs ' + cb +
                    '" style="min-width:' + w + 'px;_width:' + w +
                    'px;position:absolute;left:-6000px;top:' + h +
                    'px;z-index:' + z + ';"></div>');

            var x = $("#mailListBox_" + i), liveValue;

            that.focus(function () {
                $(this).css("color", fc).parent().css("z-index", z);
                // 提示文字自動清空
                if (hint && text) {
                    if ($.trim($(this).val()) === text) { $(this).val(""); }
                }

                $(this).keyup(function (e) {
                    s = v = $.trim($(this).val());
                    if (/@/.test(v)) { s = v.replace(/@.*/, ""); }

                    if (v.length > 0) {
                        if (e.keyCode === 38) {        // 上
                            if (index <= 0) { index = newArr.length; }
                            index--;
                        } else if (e.keyCode === 40) { // 下
                            if (index >= newArr.length - 1) { index = -1; }
                            index++;
                        } else if (e.keyCode === 13) { //  Enter
                            if (index > -1 && index < newArr.length) {
                                $(this).val($("#mailList_" + index).text());
                            }
                        } else {
                            if (/@/.test(v)) {
                                index = -1;
                                // 依 @ 後面的字串過濾候選網域
                                var site = v.replace(/.*@/, "");
                                newArr = $.map(mailArr, function (n) {
                                    return new RegExp(site).test(n) ? n : null;
                                });
                            } else {
                                newArr = mailArr;
                            }
                        }
                        x.html($.createHtml(s, newArr, index)).css("left", 0);
                        if (e.keyCode === 13 && index > -1 && index < newArr.length) {
                            x.css("left", "-6000px"); // 選完收起
                        }
                    } else {
                        x.css("left", "-6000px");
                    }
                }).blur(function () {
                    if (hint && text) {
                        if ($.trim($(this).val()) === "") { $(this).val(text); }
                    }
                    $(this).css("color", bc).unbind("keyup").parent().css("z-index", 0);
                    x.css("left", "-6000px");
                });

                // 滑鼠移過候選項時同步高亮
                $(".mailHover").live("mouseover", function () {
                    index = Number($(this).attr("id").split("_")[1]);
                    liveValue = $("#mailList_" + index).text();
                    x.children("." + cf).removeClass(cf).addClass(cl);
                    $(this).addClass(cf).removeClass(cl);
                });
            });

            x.bind("mousedown", function () {
                that.val(liveValue); // 用 mousedown 而非 click,避免先觸發 blur 導致點不到
            });
        });
    };
})(jQuery);

呼叫方式

$("#email").mailAutoComplete({
    boxClass: "out_box",     // 外部 box 樣式
    listClass: "list_box",   // 預設列表樣式
    focusClass: "focus_box", // 列表選中樣式
    markCalss: "mark_box",   // 高亮樣式
    autoClass: false,
    textHint: true,          // 提示文字自動隱藏
    hintText: "請輸入郵箱地址"
});

使用時要留意的幾件事

一、這個外掛的寬度是自適應的,內部文字變長時外層 div 會自動撐開。如果在自訂 CSS 裡寫死了寬度,非 IE6 瀏覽器下自適應就會失效。

二、不需要為最外層 box 設定 position、寬度或高度,這些外掛已經處理好了,自己再設反而容易破版。

三、只能用在單行文字輸入框上。因為沒有對其他元素型別做限制,綁錯對象可能會出現意料之外的行為。

四、$(".mailHover").live() 與 $.fn.size() 都已在 jQuery 1.9 之後移除,若在現版本使用,需分別改為 $(document).on("mouseover", ".mailHover", ...) 與 $(".justForJs").length。

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