JS輸入框郵箱自動提示(帶有demo和原始碼)

龍恩0707發表於2013-12-10

     今天在javascriptQQ群裡面 有童鞋問到 有沒有 "JS輸入框郵箱自動提示"外掛,即說都找遍了github上原始碼 都沒有看到這樣類似的外掛,然後我想了下 "JS輸入框郵箱自動提示" 和我前幾次寫的編寫簡易的JS輸入框模糊查詢 外掛 功能類似了!也google了下 到底是個什麼樣的效果,看了下也沒有什麼特別之處,所以趁著今天沒有什麼事情做的話 寫一個這樣的出來 給大家分享下 也可以自己積累下,以後如果專案中碰到類似的效果可以直接拿來用。

   說了這麼多!我們先來看看效果 看看到底是個什麼樣的,其實有時候我看別人的部落格或者程式碼時候 也是希望先看看什麼效果 然後看看他們的程式碼能不能執行,然後順著這個思路去研究他們內部程式碼,所以我底部提供了  "demo下載連結" 大家有空的話 也可以研究下我寫的程式碼 如有不足之處 請大家多多指教!好了 先瞎聊到這裡!先看看下面效果!如下圖:

原理是:一個輸入框 當我輸入任何字的時候 自動下拉相應的郵箱提示,在輸入框輸入11的時候 下拉框有所有11的郵箱 輸入其他的時候 有其他文案對應的郵箱。

同理 此外掛不需要任何html標籤,只需要一個輸入框 有相對應的class類名就ok 且父級有個class類名,其他的都不需要。內部的HTML程式碼都是自動生成的。

HTML程式碼如下:

<div class="parentCls">
    <input type="text" class="inputElem">
 </div>

其實上面的div標籤都可以不需要 只需要在input輸入框 且父級元素新增一個如上class(自定義也可以,只是在JS初始化的時候要傳入class就ok 我預設情況下 父級class叫parentCls,當前輸入框class叫inputElem,隱藏域的class叫hiddenCls,在初始化的時候 直接初始化 傳入空物件即可!)。因為頁面上可能有多個輸入框 所以需要一個父級class 來區分是那個輸入框,當然要個隱藏域 存值給開發後臺。

其中在配置項裡面 有個郵箱陣列引數 mailArr        : ["@qq.com","@qq2.com","@gmail.com","@126.com","@163.com","@hotmail.com","@yahoo.com","@yahoo.com.cn","@live.com","@sohu.com","@sina.com"] 。就是要告訴我們預設郵箱有這麼多,不管我輸入什麼 下拉框初始化時候有這麼多郵箱提示,當我精確到某一項的時候 在給個提示 精確到某一項下拉。當然由於需求的變更 郵箱這個引數可以自己初始化時候 自己根據需求配置。

程式碼風格還是和以前一樣。

實現的功能如下:

1. 支援鍵盤上下移鍵盤操作,支援滑鼠點選及按回車操作。

2. 點選document時候 除當前input輸入框之外 下拉框隱藏。當接著輸入時候 實現自動匹配等等操作。

具體不多說 就是類似於網上註冊時候 郵箱自動提示功能一樣 ,如果有任何bug的話 可以給我留言,時間也不早了 不羅嗦了!直接貼程式碼:

CSS程式碼如下:

<style>
   *{margin:0;padding:0;}
   ul,li{list-style:none;}
   .inputElem {width:198px;height:22px;line-height:22px;border:1px solid #ff4455;}
   .parentCls{width:200px;}
   .auto-tip li{width:100%;height:22px;line-height:22px;font-size:14px;}
   .auto-tip li.hoverBg{background:#ddd;cursor:pointer;}
   .red{color:red;}
   .hidden {display:none;}
  </style>

JS程式碼如下:

/**
 * 郵箱自動提示外掛
 * @constructor EmailAutoComplete
 * @ options {object} 可配置項
 */

 function EmailAutoComplete(options) {
    
    this.config = {
        targetCls      :  '.inputElem',       // 目標input元素
        parentCls      :  '.parentCls',       // 當前input元素的父級類
        hiddenCls      :  '.hiddenCls',       // 當前input隱藏域 
        searchForm     :  '.jqtransformdone', //form表單
        hoverBg        :  'hoverBg',          // 滑鼠移上去的背景
        inputValColor  :  'red',              // 輸入框輸入提示顏色
        mailArr        : ["@qq.com","@qq2.com","@gmail.com","@126.com","@163.com","@hotmail.com","@yahoo.com","@yahoo.com.cn","@live.com","@sohu.com","@sina.com"], //郵箱陣列
        isSelectHide   : true,                // 點選下拉框 是否隱藏 預設為true
        callback       : null                 // 點選某一項回撥函式
    };
    this.cache = {
        onlyFlag            : true,     // 只渲染一次
        currentIndex        : -1,
        oldIndex            : -1
    };
    
    this.init(options);
 }

EmailAutoComplete.prototype = {
    
    constructor: EmailAutoComplete,

    init: function(options){
        this.config = $.extend(this.config,options || {});

        var self = this,
            _config = self.config,
            _cache = self.cache;
        
        $(_config.targetCls).each(function(index,item){
            
            $(item).keyup(function(e){
                var target = e.target,
                    targetVal = $.trim($(this).val()),
                    keycode = e.keyCode,
                    elemHeight = $(this).outerHeight(),
                    elemWidth = $(this).outerWidth(),
                    parentNode = $(this).closest(_config.parentCls);
                
                $(parentNode).css({'position':'relative'});
                // 如果輸入框值為空的話 那麼下拉框隱藏
                if(targetVal == '') {
                    $(item).attr({'data-html':''});
                    // 給隱藏域賦值
                    $(_config.hiddenCls,parentNode).val('');

                    _cache.currentIndex = -1;
                    _cache.oldIndex = -1;
                    $(".auto-tip",parentNode) && !$(".auto-tip",parentNode).hasClass('hidden') && $(".auto-tip",parentNode).addClass('hidden');
                    self._removeBg(parentNode);
                }else {
                    
                    $(item).attr({'data-html':targetVal});

                    // 給隱藏域賦值
                    $(_config.hiddenCls,parentNode).val(targetVal);
                    
                    $(".auto-tip",parentNode) && $(".auto-tip",parentNode).hasClass('hidden') && $(".auto-tip",parentNode).removeClass('hidden');
                    // 渲染下拉框內容
                    self._renderHTML({keycode:keycode,e:e,target:target,targetVal:targetVal,height:elemHeight,width:elemWidth,parentNode:parentNode});
                }
                
                
            });
        });
        
       // 阻止form表單預設enter鍵提交
       $(_config.searchForm).each(function(index,item) {
            $(item).keydown(function(e){
                 var keyCode = e.keyCode;
                 if(keyCode == 13) {
                     return false;
                 }
            });
       });

       // 點選文件document時候 下拉框隱藏掉
       $(document).click(function(e){
          e.stopPropagation();
          var target = e.target,
              tagCls = _config.targetCls.replace(/^\./,'');

          if(!$(target).hasClass(tagCls)) {
             $('.auto-tip') && $('.auto-tip').each(function(index,item){
                 !$(item).hasClass('hidden') && $(item).addClass('hidden');
             });
          }
       });
    },
    /*
     * 渲染下拉框提示內容
     * @param cfg{object}
     */
    _renderHTML: function(cfg) {
        var self = this,
            _config = self.config,
            _cache = self.cache,
            curVal;
        var curIndex = self._keyCode(cfg.keycode);
        
        $('.auto-tip',cfg.parentNode).hasClass('hidden') && $('.auto-tip',cfg.parentNode).removeClass('hidden');
        if(curIndex > -1){
            // 鍵盤上下操作
            self._keyUpAndDown(cfg.targetVal,cfg.e,cfg.parentNode);
        }else {
            if(/@/.test(cfg.targetVal)) {
                curVal = cfg.targetVal.replace(/@.*/,'');
            }else {
                curVal = cfg.targetVal;
            }
            if(_cache.onlyFlag) {
                $(cfg.parentNode).append('<input type="hidden" class="hiddenCls"/>');
                var wrap = '<ul class="auto-tip">';

                for(var i = 0; i < _config.mailArr.length; i++) {

                    wrap += '<li class="p-index'+i+'">'+'<span class="output-num"></span><em class="em" data-html="'+_config.mailArr[i]+'">'+_config.mailArr[i]+'</em></li>';
                }
                wrap += '</ul>';
                _cache.onlyFlag = false;
                $(cfg.parentNode).append(wrap);
                $('.auto-tip',cfg.parentNode).css({'position':'absolute','top':cfg.height,'width':cfg.width - 2 + 'px','left':0,
                    'border':'1px solid #ccc','z-index':10000});
            }
            
            // 給所有li新增屬性 data-html
            $('.auto-tip li',cfg.parentNode).each(function(index,item){
                $('.output-num',item).html(curVal);
                !$('.output-num',item).hasClass(_config.inputValColor) && 
                $('.output-num',item).addClass(_config.inputValColor);
                var emVal = $.trim($('.em',item).attr('data-html'));
                $(item).attr({'data-html':curVal + '' +emVal});
            });

            // 精確匹配內容
            self._accurateMate({target:cfg.target,parentNode:cfg.parentNode});

            // 滑鼠移到某一項li上面時候
            self._itemHover(cfg.parentNode);
            
            // 點選對應的項時
            self._executeClick(cfg.parentNode);
        }
        
    },
    /**
     * 精確匹配某項內容
     */
    _accurateMate: function(cfg) {
        var self = this,
            _config = self.config,
            _cache = self.cache;
        
        var curVal = $.trim($(cfg.target,cfg.parentNode).attr('data-html')),
            newArrs = [];
        if(/@/.test(curVal)) {
            
            // 獲得@ 前面 後面的值
            var prefix = curVal.replace(/@.*/, ""),
                suffix = curVal.replace(/.*@/, "");

            $.map(_config.mailArr,function(n){
                var reg = new RegExp(suffix);
                if(reg.test(n)) {
                    newArrs.push(n);
                }
            });
            if(newArrs.length > 0) {
                $('.auto-tip',cfg.parentNode).html('');
                $(".auto-tip",cfg.parentNode) && $(".auto-tip",cfg.parentNode).hasClass('hidden') && 
                $(".auto-tip",cfg.parentNode).removeClass('hidden');

                var html = '';
                for(var j = 0, jlen = newArrs.length; j < jlen; j++) {
                    html += '<li class="p-index'+j+'">'+'<span class="output-num"></span><em class="em" data-html="'+newArrs[j]+'">'+newArrs[j]+'</em></li>';
                }
                $('.auto-tip',cfg.parentNode).html(html);
                
                // 給所有li新增屬性 data-html
                $('.auto-tip li',cfg.parentNode).each(function(index,item){
                    $('.output-num',item).html(prefix);
                    !$('.output-num',item).hasClass(_config.inputValColor) && 
                    $('.output-num',item).addClass(_config.inputValColor);

                    var emVal = $.trim($('.em',item).attr('data-html'));
                    
                    $(item).attr('data-html','');
                    $(item).attr({'data-html':prefix + '' +emVal});
                });

                // 精確匹配到某項時候 讓當前的索引等於初始值
                _cache.currentIndex = -1;
                _cache.oldIndex = -1;
                
                $('.auto-tip .output-num',cfg.parentNode).html(prefix);

                // 滑鼠移到某一項li上面時候
                self._itemHover(cfg.parentNode);

                // 點選對應的項時
                self._executeClick(cfg.parentNode);
            }else {
                $(".auto-tip",cfg.parentNode) && !$(".auto-tip",cfg.parentNode).hasClass('hidden') && 
                $(".auto-tip",cfg.parentNode).addClass('hidden');
                $('.auto-tip',cfg.parentNode).html('');
            }
        }
    },
    /*
     * 滑鼠移到某一項li上時
     */
    _itemHover: function(parentNode) {
        var self = this,
            _config = self.config,
            _cache = self.cache;
        $('.auto-tip li',parentNode).hover(function(index,item) {
            !$(this).hasClass(_config.hoverBg) && $(this).addClass(_config.hoverBg);
        },function() {
            $(this).hasClass(_config.hoverBg) && $(this).removeClass(_config.hoverBg);
        });
    },
    /*
     * 當輸入框值為空時候 li項都刪掉class hoverBg
     */
    _removeBg: function(parentNode){
        var self = this,
            _config = self.config;

        $(".auto-tip li",parentNode).each(function(index,item){
            $(item).hasClass(_config.hoverBg) && $(item).removeClass(_config.hoverBg);
        });    
    },
    /**
     * 鍵盤上下鍵操作
     */
     _keyUpAndDown: function(targetVal,e,parentNode) {
        var self = this,
            _cache = self.cache,
            _config = self.config;

        // 如果請求成功後 返回了資料(根據元素的長度來判斷) 執行以下操作
        if($('.auto-tip' + ' li',parentNode) && $('.auto-tip' + ' li').length > 0) {

            var plen = $('.auto-tip' + ' li',parentNode).length,
                keyCode = e.keyCode;
                _cache.oldIndex = _cache.currentIndex;
            

            // 上移操作
            if(keyCode == 38) {
                if(_cache.currentIndex == -1) {
                    _cache.currentIndex = plen - 1;
                }else {
                    _cache.currentIndex = _cache.currentIndex - 1;
                    if(_cache.currentIndex < 0) {
                        _cache.currentIndex = plen - 1;
                    }
                }
                if(_cache.currentIndex !== -1) {
                    

                    !$('.auto-tip .p-index'+_cache.currentIndex,parentNode).hasClass(_config.hoverBg) &&
                    $('.auto-tip .p-index'+_cache.currentIndex,parentNode).addClass(_config.hoverBg).siblings().removeClass(_config.hoverBg);

                    var curAttr = $('.auto-tip' + ' .p-index'+_cache.currentIndex,parentNode).attr('data-html');
                    $(_config.targetCls,parentNode).val(curAttr);
                    
                    // 給隱藏域賦值
                    $(_config.hiddenCls,parentNode).val(curAttr);
                }

            }else if(keyCode == 40) { //下移操作
                if(_cache.currentIndex == plen - 1) {
                    _cache.currentIndex = 0;
                }else {
                    _cache.currentIndex++;
                    if(_cache.currentIndex > plen - 1) {
                        _cache.currentIndex = 0;
                    }
                }

                if(_cache.currentIndex !== -1) {
                    
                    !$('.auto-tip .p-index'+_cache.currentIndex,parentNode).hasClass(_config.hoverBg) &&
                    $('.auto-tip .p-index'+_cache.currentIndex,parentNode).addClass(_config.hoverBg).siblings().removeClass(_config.hoverBg);
                    
                    var curAttr = $('.auto-tip' + ' .p-index'+_cache.currentIndex,parentNode).attr('data-html');
                    $(_config.targetCls,parentNode).val(curAttr);
                    // 給隱藏域賦值
                    $(_config.hiddenCls,parentNode).val(curAttr);
                }
                
            }else if(keyCode == 13) { //回車操作
                var curVal = $('.auto-tip' + ' .p-index'+_cache.oldIndex,parentNode).attr('data-html');
                $(_config.targetCls,parentNode).val(curVal);
                
                // 給隱藏域賦值
                $(_config.hiddenCls,parentNode).val(curVal);

                if(_config.isSelectHide) {
                     !$(".auto-tip",parentNode).hasClass('hidden') && $(".auto-tip",parentNode).addClass('hidden');
                 }
                 _config.callback && $.isFunction(_config.callback) && _config.callback();

                _cache.currentIndex = -1;
                _cache.oldIndex = -1;
                
            }
        }
     },
     _keyCode: function(code) {
         var arrs = ['17','18','38','40','37','39','33','34','35','46','36','13','45','44','145','19','20','9'];
         for(var i = 0, ilen = arrs.length; i < ilen; i++) {
             if(code == arrs[i]) {
                 return i;
             }
         }
         return -1;
     },
    /**
      * 當資料相同的時 點選對應的項時 返回資料
      */
     _executeClick: function(parentNode) {
        
         var _self = this,
             _config = _self.config;

         $('.auto-tip' + ' li',parentNode).unbind('click');
         $('.auto-tip' + ' li',parentNode).bind('click',function(e){
              var dataAttr = $(this).attr('data-html');

              $(_config.targetCls,parentNode).val(dataAttr);
              if(_config.isSelectHide) {
                  !$(".auto-tip",parentNode).hasClass('hidden') && $(".auto-tip",parentNode).addClass('hidden');
              }
              // 給隱藏域賦值
              $(_config.hiddenCls,parentNode).val(dataAttr);
              _config.callback && $.isFunction(_config.callback) && _config.callback();
              
         });
     }
};

// 初始化
$(function() {
    new EmailAutoComplete({});
});
View Code

JS郵箱自動提示外掛demo下載

相關文章