jQuery 实现邮箱输入自动提示功能:二

上篇文章写到了一个不错的jquery实现邮箱输入自动提示功能,发现还有一个不错的自动提示插件:

先展示结果如图:

html代码:

<center>
h1>输入邮箱试试!</br />
div class="parentCls"><input type="text" class="inputElem"></div>

css代码:

@charset "utf-8";
* {    outline:none;
    margin:0;
    padding:
    font-family:microsoft yahei;
}
ul,li {
    list-style:none;
}
.inputElem {
    width:198px;
    height:22px;
    line-height:
    border:1px solid #ccc;
}
.parentCls {200px;auto; margin:0 auto;
}
.auto-tip li {100%;
    text-align:left;
    font-size:14px;
}

.auto-tip li.hoverBg {
    background:#ddd;
    cursor:pointer;
}
.auto-tip li em{font-style:normal;}
.red {
    color:#333;
}
.hidden {
    display:none;
}

jquery代码:

/**
 * 邮箱自动提示插件
 * @constructor EmailAutoComplete
 * @ options {object} 可配置项
 */
 function EmailAutoComplete(options) {
    
    this.config = {
        targetCls      :  '.inputElem',// 目标input元素
        parentCls      :  '.parentCls',1)"> 当前input元素的父级类
        hiddenCls      :  '.hiddenCls',1)"> 当前input隐藏域 
        searchForm     :  '.jqtransformdone',1)">form表单
        hoverBg        :  'hoverBg',1)"> 鼠标移上去的背景
        inputValColor  :  'black',1)"> 输入框输入提示颜色
        mailArr        : ["@qq.com","@gmail.com","@126.com","@163.com","@hotmail.com","@yahoo.com","@yahoo.com.cn","@live.com","@sohu.com","@sina.com"],1)">邮箱数组
        isSelectHide   : true,1)"> 点击下拉框 是否隐藏 默认为true
        callback       : null                  点击某一项回调函数
    };
    this.cache = {
        onlyFlag            :  只渲染一次
        currentIndex        : -1,oldIndex            : -1
    };
    
    this.init(options);
 }

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

        var self =  self.config,_cache = self.cache;
        
        $(_config.targetCls).each((index,item){
            
            $(item).keyup((e){
                var target = e.target,targetVal = $.trim($().val()),keycode = e.keyCode,elemHeight = $().outerHeight(),elemWidth = $().outerWidth(),parentNode = $().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).removeClass('hidden');
                     渲染下拉框内容
                    self._renderHTML({keycode:keycode,e:e,target:target,targetVal:targetVal,height:elemHeight,width:elemWidth,parentNode:parentNode});
                }
                
                
            });
        });
        
        阻止form表单默认enter键提交
       $(_config.searchForm).each((e){
                 var keyCode = e.keyCode;
                 if(keyCode == 13) {
                     return false;
                 }
            });
       });

        点击文档document时候 下拉框隐藏掉
       $(document).click((e){
          e.stopPropagation();
          );

          if(!$(target).hasClass(tagCls)) {
             $('.auto-tip') && $('.auto-tip').each();
             });
          }
       });
    },
     * 渲染下拉框提示内容
     * @param cfg{object}
     */
    _renderHTML: (cfg) {
         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);
        } {
            if(/@/.test(cfg.targetVal)) {
                curVal = cfg.targetVal.replace(/@.*/,1)">);
            } {
                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 = ;
                $(cfg.parentNode).append(wrap);
                $('.auto-tip',cfg.parentNode).css({'position':'absolute','top':cfg.height,'width':cfg.width - 2 + 'px','left':0});
            }
            
             给所有li添加属性 data-html
            $('.auto-tip li',cfg.parentNode).each(!$('.output-num',item).hasClass(_config.inputValColor) && 
                $('.output-num'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);
        }
        
    },1)">*
     * 精确匹配某项内容
     
    _accurateMate:  self.cache;
        
        var curVal = $.trim($(cfg.target,cfg.parentNode).attr('data-html')),newArrs = [];
        .test(curVal)) {
            
             获得@ 前面 后面的值
            var prefix = curVal.replace(/@.*/,""),suffix = curVal.replace(/.*@/,1)">);

            $.map(_config.mailArr,1)">(n){
                var reg = new RegExp(suffix);
                (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",1)">);

                var html = '';
                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' 给所有li添加属性 data-html
                $('.auto-tip li',item){
                    $('.output-num' 
                    $('.output-num'));
                    
                    $(item).attr('data-html',1)">);
                    $(item).attr({'data-html':prefix + '' +emVal});
                });

                 精确匹配到某项时候 让当前的索引等于初始值
                _cache.currentIndex = -1;
                _cache.oldIndex = -1;
                
                $('.auto-tip .output-num'                self._itemHover(cfg.parentNode);

                                self._executeClick(cfg.parentNode);
            } {
                $(".auto-tip",cfg.parentNode) && !$(".auto-tip",cfg.parentNode).addClass('hidden');
                $('.auto-tip',1)">);
            }
        }
    },1)">
     * 鼠标移到某一项li上时
     
    _itemHover: (parentNode) {
         self.cache;
        $('.auto-tip li',parentNode).hover(this).hasClass(_config.hoverBg) && $().addClass(_config.hoverBg);
        },1)">() {
            $().removeClass(_config.hoverBg);
        });
    },1)">
     * 当输入框值为空时候 li项都删掉class hoverBg
     
    _removeBg: (parentNode){
         self.config;

        $(".auto-tip li",parentNode).each( $(item).removeClass(_config.hoverBg);
        });    
    },1)">*
     * 键盘上下键操作
     
     _keyUpAndDown: (targetVal,e,parentNode) {
         self.config;

         如果请求成功后 返回了数据(根据元素的长度来判断) 执行以下操作
        if($('.auto-tip' + ' li',parentNode) && $('.auto-tip' + ' li').length > 0) {

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

             上移操作
            if(keyCode == 38) {
                if(_cache.currentIndex == -1) {
                    _cache.currentIndex = plen - 1;
                } {
                    _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);
                    
                    else if(keyCode == 40) { 下移操作
                if(_cache.currentIndex == plen - 1) {
                    _cache.currentIndex = 0 {
                    _cache.currentIndex++if(_cache.currentIndex > plen - 1) {
                        _cache.currentIndex = 0;
                    }
                }

                ) {
                    
                    !$('.auto-tip .p-index'+_cache.currentIndex,parentNode).addClass(_config.hoverBg).siblings().removeClass(_config.hoverBg);
                    
                    if(keyCode == 13) { 回车操作
                var curVal = $('.auto-tip' + ' .p-index'+_cache.oldIndex,1)">);
                $(_config.targetCls,parentNode).val(curVal);
                
                                $(_config.hiddenCls,parentNode).val(curVal);

                (_config.isSelectHide) {
                     !$(".auto-tip",1)">);
                 }
                 _config.callback && $.isFunction(_config.callback) && _config.callback();

                _cache.currentIndex = -1;
                
            }
        }
     },_keyCode: (code) {
         var arrs = ['17','18','38','40','37','39','33','34','35','46','36','13','45','44','145','19','20','9'];
         var i = 0,ilen = arrs.length; i < ilen; i++) {
             if(code == arrs[i]) {
                 return i;
             }
         }
         return -1;
     },1)">*
      * 当数据相同的时 点击对应的项时 返回数据
      
     _executeClick: (parentNode) {
        
         var _self =  _self.config;

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

              $(_config.targetCls,parentNode).val(dataAttr);
              (_config.isSelectHide) {
                  !$(".auto-tip",1)">);
              }
                            $(_config.hiddenCls,parentNode).val(dataAttr);
              _config.callback && $.isFunction(_config.callback) && _config.callback();
              
         });
     }
};
View Code

调用方式:

 初始化
$(() {
     EmailAutoComplete({});
});

需要查看例子,请点击下载demo

相关文章

1.第一步 设置响应头 header(&#39;Access-Control-Allow...
$.inArray()方法介绍 $.inArray()函数用于在数组中搜索指定的...
jquery.serializejson.min.js的妙用 关于这个jquery.seriali...
JS 将form表单数据快速转化为object对象(json对象) jaymou...
jQuery插件之jquery.spinner数字智能增减插件 参考地址:http...