基于jquery的邮箱输入联想插件开发

js代码:

/*create by code_bunny 20140701
  973295131@qq.com
  https://github.com/OOP-Code-Bunny
*/
(function ($) {
    $.fn.autoComplate = function (opts) {
        this.each(function () {
            init.call(this, opts);
        });
        return this;
    };

    function init(opts) {
        var defaultOption = {
            textInput: $(this),            //文本输入框
            emailBox: $(this).next(),      //用于放置联想邮箱的框
            links:['163.com','qq.com','126.com','gmail.com','yeah.net','hotmail.com','sina.com','sina.cn','sohu.com']  //联想内容,
        };

        var options = $.extend(defaultOption, opts);

        var func = {};

        func.init = function(){
            this.timeOut = null;
            this.cur = null;
            this.emailList = [];
            this.aUl = $('<ul>');
            for(var i=0; i<this.links.length; i++){
                var aLi = $('<li>');
                this.emailList.push(aLi);
                this.aUl.append(aLi);
                aLi.bind('mousedown',func.chooseLi.bind(options));
            }
            this.emailBox.append(this.aUl);
            this.textInput.bind('keydown',func.keyDownFun.bind(this)).bind('keyup',func.keyUpFun.bind(this)).bind('blur',func.textBlur.bind(this));
            return this;
        };

        func.chooseLi = function(e){
            this.textInput.val($(e.target).text());
        };

        func.keyDownFun = function(e){
            func.clearTO.call(this);
            if(e.keyCode==13){
                return func.pressEnter.call(this);
            }
            else if (e.keyCode==40) {
                return func.upAndDown.apply(this,[true]);
            }
            else if(e.keyCode==38){
                return func.upAndDown.apply(this,[false]);
            }
            this.timeOut = setTimeout(func.timeout.bind(this),0)
        };

        func.keyUpFun = function(e){
            func.clearTO.call(this);
            if (func.ifNotText.apply(this, [e.keyCode])) return;
            this.timeOut = setTimeout(func.timeout.bind(this),0)
        };

        func.pressEnter = function(){
            return (this.cur === null) ?  func.noCurPressEnter.call(this) : func.curPressEnter.call(this)
        };

        func.noCurPressEnter = function(){
            return (this.textInput.val().indexOf('@')>0 && this.textInput.val().indexOf('@')<this.textInput.val().length-1) ? this.textInput.blur() : this.textInput.val(this.emailList[0].text()).blur();
        };

        func.curPressEnter = function(){
            return this.textInput.val(this.emailBox.find('li:visible').eq(this.cur).text()).blur();
        };

        //上下键函数,参数表示上下,true为下,false为上
        func.upAndDown = function(direct){
            this.length = this.emailBox.find('li:visible').length;
            var start = direct ? 0 : this.length-1;
            if(this.cur === null) {
                this.cur = start;
                this.emailBox.find('li:visible').eq(this.cur).addClass('cur');
            }
            else {
                func.removeCur.call(this);
                var end = direct ? options.length-1 : 0;
                this.cur = this.cur == end ? start : (direct ? this.cur+1 : this.cur-1);
                this.emailBox.find('li:visible').eq(this.cur).addClass('cur');
            }
        };

        func.timeout = function(){
            return this.textInput.val() == '' ? this.emailBox.hide() : func.match.apply(this,[this.textInput.val()])
        };

        func.ifNotText = function(num){
            return num == 13 || num == 40 || num == 38
        };

        func.match = function(content){
            func.removeCur.call(this).emailBox.show();
            this.cur = null;
            var contentPrv = content.split('@')[0];
            var contentNext = content.split('@')[1] || '';
            for(var i=0; i<this.links.length; i++){
                this.emailList[i] = this.links[i].indexOf(contentNext)!=0 ? this.emailList[i].text(contentPrv+'@'+this.links[i]).hide() : this.emailList[i].text(contentPrv+'@'+this.links[i]).show();
            }
        };

        func.textBlur = function(){
            func.clearTO.call(this);
            this.cur = null;
            func.removeCur.call(this);
            this.emailBox.hide();
            return this
        };

        func.removeCur = function(){
            $.each(this.emailList,function(){
                $(this).removeClass('cur')
            });
            return this
        };

        func.clearTO = function(){
            clearTimeout(this.timeOut);
            this.timeOut = null;
        };

        func.bindFocus = function(){
            this.textInput.bind('keydown',func.keyDownFun.bind(this)).bind('keyup',func.keyUpFun.bind(this));
        };

        func.init.call(options);
    }
})(jQuery);

html代码:

                  <div class="inpt">
                    <div>
                      <input type="text" class="email text" name="email" >
                      <div class="textlist" style="display:none">
                      </div>
                    </div>
                  </div>

1. 创建ul,li,插入到emailBox中,同时给li绑定点击事件(必须是mousedown事件,不能是click事件)为chooseLi方法.  (查看→3)

    因为点击的时候元素就会失去焦点,触发input的blur事件,但是必须让li的点击事件发生在input的blur事件之前,所以要用mousedown事件

2.

    ①. 给input的keydown事件绑定keyDownFun方法.   (查看→5)

    ②. 给input的keyup事件绑定keyUpFun方法.   (查看→6)

    ③. 给input的blur事件绑定textBlur方法.   (查看→4)

3. chooseLi方法,选取点击项填充input(点击后也会触发input的blur事件)

4. textBlur方法,清除timeOut,清除cur,删除li的cur类名,隐藏联想框

5. keyDownFun方法:

    ①清除timeout(防止输入太快出现bug)

    ②如果按下的是回车键,调用pressEnter方法,return   (查看→7)

    ③如果按下的是'下'键,调用upAndDown方法,传入true,return   (查看→10)

    ④如果按下的是'上'键,调用upAndDown方法,传入false,return   (查看→10)

    ⑤设置timeOut为0秒后执行timeout方法,使输入内容和联想内容同步显示   (查看→11)

6. keyUpFun方法:

    ①清除timeout(防止输入太快出现bug)

    ②调用ifNotText方法,传入e.keycode作为参数,判断按下的是否是'回车,下,上',如果是的话,直接return

    * 还是需要判断输入的是文字,还是'上,下,回车',如果是'上,下,回车',则不能直接再次匹配,因为匹配的过程就包括了重置cur.

    ③设置timeOut为0秒后执行timeout方法   (查看→11)

    * 显示联想的内容在keydown和keyup时都要发生(如果只定义其中一个,输入快了会有时不同步),而且即使发生两次,也没有问题. 但是回车,上,下,这三个键的事件只能绑定keydown,因为它每次按键只能被调用一次.

7. pressEnter方法:

    ①如果当前没有cur项,则调用noCurPressEnter方法    (查看→8)

    ②如果当前有cur项,则调用curPressEnter方法    (查看→9)

    *判断是否有cur项,不能使用 if(cur),或者if(!cur),因为cur的值有可能是0,是0的时候会得到和想要的值不同的结果

8. noCurPressEnter方法:

    判断输入框里是否有'@'符,并且@符不在最后一位,   

    ①已经有@符并且不在最后一位,则表示已输入想要的结果,直接触发input的blur事件.

    ②输入的内容里没有@符,或者@符后面没有内容,则表示没有输入完整邮箱,将第一个li里的内容填充到input,再触发input的blur事件

9. curPressEnter方法:

    直接将cur项的值填充到input,然后input失去焦点

10. upAndDown方法:

    ①定义length属性为当前显示的li项的数量

    ②判断当前是否有cur项,有的话将cur转到下一个或上一个(根据传入的参数判断是上还是下)

    ③没有的话将cur转到第一个或者最后一个(根据传入的参数判断是上还是下)

11. timeout方法:

    ①如果input框内容为空,隐藏emailBox

    ②如果input框内容不为空,调用match方法    (查看→13)

12. ifNotText方法:

     判断是否是'回车,下,上'键,是其中之一的话,返回true

13. match方法:

     ①清空cur项

     *如果已经通过键盘选择了一个邮箱,又接着输入内容,则原来被选中的项必须清空. 如果不清空,新输入的内容会导致筛选条件的变化,导致显示的项也发生变化,这时假设接着按'下',则cur的改变不是新筛选出的显示项,依然是原来的显示项,导致错误.

     ②让emailBox显示

     ③按照@符分割输入的内容

     ④每个li的内容应该就是@前面的内容+links的内容

     ⑤让@后面的内容去匹配每个links的开头,匹配成功的显示,匹配失败的隐藏

github地址: https://github.com/OOP-Code-Bunny/ocj-index-v3.0.0/blob/master/common/js/common/jquery.autoComplate.js     

原文地址:https://www.cnblogs.com/liulangmao/p/3817959.html