inputSuggest邮箱提示自动补全js插件

inputSuggest在文本框输入字符时提示,类似Windows的“自动完成”功能,当在文本框输入字符时,与此相关的内容会显示在文本框的下边,你可随时使用键盘或鼠标点选那些提示,你就不用输入了。像QQ邮箱提示、百度的搜索框提示、淘宝的商品搜索提示等,现在有不少的网站都有类似效果,以提升用户体验。

使用方法:

new InputSuggest({ 
  input HTMLInputElement 必选 
  data Array ['sina.cn','sina.com','2008.sina.com','vip.sina.com.cn'] 必选 
  containerCls 容器className 
  itemCls 容器子项className 
  activeCls 高亮子项className 
  width 宽度设置 此项将覆盖containerCls的width 
  opacity 透明度设置 此项将覆盖containerCls的opacity……

例子:

window.onload = 


function () {
    var regSuggest = new InputSuggest({
        input: document.getElementById('rEmail'),
        data: ['qq.com', '163.com', 'sina.com', 'vip.sina.com', '126.com', 'hotmail.com', 'sina.cn','gmail.com', 'sohu.com', 'yahoo.cn', '139.com', 'wo.com.cn', '189.cn']
    });
    var logSuggest = new InputSuggest({
        input: document.getElementById('lEmail'),
        data: ['qq.com', '163.com', 'sina.com', 'vip.sina.com', '126.com', 'hotmail.com', 'sina.cn','gmail.com', 'sohu.com', 'yahoo.cn', '139.com', 'wo.com.cn', '189.cn']
    });
}
<!DOCTYPE HTML>
<html>
<head>
<title>inputSuggest输入字符时提示</title>
<style type="text/css">
body{margin:0;padding:0;}
input{width:200px;}
.suggest-container{border:1px solid #C1C1C1;visibility:hidden;}
.suggest-item{padding:3px 2px;}
.suggest-active {background:#33CCFF;color:white;padding:3px 2px;}            
</style>
<script type="text/javascript">
function InputSuggest(opt){
    this.win = null;
    this.doc = null;    
    this.container = null;
    this.items = null;
    this.input = opt.input || null;
    this.containerCls = opt.containerCls || 'suggest-container';
    this.itemCls = opt.itemCls || 'suggest-item';
    this.activeCls = opt.activeCls || 'suggest-active';
    this.width = opt.width;
    this.opacity = opt.opacity;
    this.data = opt.data || [];
    this.active = null;
    this.visible = false;
    this.init();
}
InputSuggest.prototype = {
    init: function(){
        this.win = window;
        this.doc = window.document;
        this.container = this.$C('div');
        this.attr(this.container, 'class', this.containerCls);                
        this.doc.body.appendChild(this.container);
        this.setPos();
        var _this = this, input = this.input;        

        this.on(input,'keyup',function(e){
            if(input.value==''){
                _this.hide();
            }else{
                _this.onKeyup(e);
            }
            
        });
        // blur会在click前发生,这里使用mousedown
        this.on(input,'blur',function(e){
            _this.hide();            
        });
        this.onMouseover();
        this.onMousedown();
        
    },
    $C: function(tag){
        return this.doc.createElement(tag);
    },
    getPos: function (el){
        var pos=[0,0], a=el;
        if(el.getBoundingClientRect){
            var box = el.getBoundingClientRect();
            pos=[box.left,box.top];
        }else{
            while(a && a.offsetParent){
                pos[0] += a.offsetLeft;
                pos[1] += a.offsetTop;
                a = a.offsetParent
            }            
        }
        return pos;
    },    
    setPos: function(){
        var input = this.input, 
            pos = this.getPos(input), 
            brow = this.brow, 
            width = this.width,
            opacity = this.opacity,
            container = this.container;
        container.style.cssText =
            'position:absolute;overflow:hidden;left:' 
            + pos[0] + 'px;top:'
            + (pos[1]+input.offsetHeight) + 'px;width:'
            // IE6/7/8/9/Chrome/Safari input[type=text] border默认为2,Firefox为1,因此取offsetWidth-2保证与FF一致
            + (brow.firefox ? input.clientWidth : input.offsetWidth-2) + 'px;';
        if(width){
            container.style.width = width + 'px';
        }
        if(opacity){
            if(this.brow.ie){
                container.style.filter = 'Alpha(Opacity=' + opacity * 100 + ');';
            }else{
                container.style.opacity = (opacity == 1 ? '' : '' + opacity);
            }            
        }
    },
    show: function(){
        this.container.style.visibility = 'visible';
        this.visible = true;
    },
    hide: function(){
        this.container.style.visibility = 'hidden';
        this.visible = false;    
    },
    attr: function(el, name, val){
        if(val === undefined){
            return el.getAttribute(name);
        }else{
            el.setAttribute(name,val);
            name=='class' && (el.className = val);            
        }
    },
    on: function(el, type, fn){
        el.addEventListener ? el.addEventListener(type, fn, false) : el.attachEvent('on' + type, fn);
    },
    un: function(el, type, fn){
        el.removeEventListener ? el.removeEventListener(type, fn, false) : el.detachEvent('on' + type, fn);
    },
    brow: function(ua){
        return {
            ie: /msie/.test(ua) && !/opera/.test(ua),
            opera: /opera/.test(ua),
            firefox: /firefox/.test(ua)
        };
    }(navigator.userAgent.toLowerCase()),
    onKeyup: function(e){
        var container = this.container, input = this.input, iCls = this.itemCls, aCls = this.activeCls;
        if(this.visible){
            switch(e.keyCode){
                case 13: // Enter
                    if(this.active){
                        input.value = this.active.firstChild.data;
                        this.hide();
                    }                    
                    return;
                case 38: // 方向键上
                    if(this.active==null){
                        this.active = container.lastChild;
                        this.attr(this.active, 'class', aCls);
                        input.value = this.active.firstChild.data;
                    }else{
                        if(this.active.previousSibling!=null){
                            this.attr(this.active, 'class', iCls);
                            this.active = this.active.previousSibling;
                            this.attr(this.active, 'class', aCls);
                            input.value = this.active.firstChild.data;
                        }else{
                            this.attr(this.active, 'class', iCls);
                            this.active = null;
                            input.focus();
                            input.value = input.getAttribute("curr_val");
                        }
                    }
                    return;
                case 40: // 方向键下
                    if(this.active==null){
                        this.active = container.firstChild;
                        this.attr(this.active, 'class', aCls);
                        input.value = this.active.firstChild.data;
                    }else{            
                        if(this.active.nextSibling!=null){
                            this.attr(this.active, 'class', iCls);
                            this.active = this.active.nextSibling;
                            this.attr(this.active, 'class', aCls);
                            input.value = this.active.firstChild.data;
                           }else{
                        this.attr(this.active, 'class', iCls);
                            this.active = null;
                            input.focus();
                        input.value = input.getAttribute("curr_val");
                        }
                    }
                    return;

            }
        }    
        if(e.keyCode==27){ // ESC键
            this.hide();
            input.value = this.attr(input,'curr_val');
            return;
        }    
        if(input.value.indexOf('@')!=-1){return;}
        this.items = [];
        
        if(this.attr(input,'curr_val')!=input.value){
            this.container.innerHTML = '';
            for(var i=0,len=this.data.length;i<len;i++){
                var item = this.$C('div');
                this.attr(item, 'class', this.itemCls);
                item.innerHTML = input.value + '@' + this.data[i];
                this.items[i] = item;
                this.container.appendChild(item);
            }
            this.attr(input,'curr_val',input.value);        
        }

        this.show();
    },
    onMouseover: function(){
        var _this = this, icls = this.itemCls, acls = this.activeCls;
        this.on(this.container,'mouseover',function(e){
            var target = e.target || e.srcElement;
            if(target.className == icls){
                if(_this.active){
                    _this.active.className = icls;
                }
                target.className = acls;
                _this.active = target;
            }
        });
    },
    onMousedown: function(){
        var _this = this;    
        this.on(this.container,'mousedown',function(e){
            var target = e.target || e.srcElement;
            _this.input.value = target.innerHTML;
            _this.hide();
        });
    }
}    
        </script>
        <script type="text/javascript">
            window.onload = function(){                
                var sinaSuggest = new InputSuggest({
                    input: document.getElementById('sina'),
                    data: ['sina.cn','sina.com','vip.sina.com.cn','2008.sina.com','263.sina.com']
                });
                var sohuSuggest = new InputSuggest({
                    width: 300,
                    opacity: 0.3,
                    input: document.getElementById('sohu'),
                    data: ['sohu.com','sogou.com','chinaren.com','vip.sohu.com','sohu.net','2008.sohu.com','sms.sohu.com']
                });
            }
        </script>
    </head>
    <body>
        <div style="width:400px;margin:30px auto;text-align:center;">
            <label>新浪</label>
            <input type="text" id="sina"/>
            <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
            <label>搜狐</label>
            <input type="text" id="sohu"/>            
        </div>

    </body>
</html>

js代码:

/**
 * new InputSuggest({
 *       input         HTMLInputElement 必选
 *       data             Array ['sina.cn','sina.com','2008.sina.com','vip.sina.com.cn'] 必选
 *       containerCls    容器className
 *       itemCls        容器子项className
 *       activeCls        高亮子项className
 *       width         宽度设置 此项将覆盖containerCls的width
 *    opacity        透明度设置 此项将覆盖containerCls的opacity
 * });
 */

function InputSuggest(opt){
    this.win = null;
    this.doc = null;    
    this.container = null;
    this.items = null;
    this.input = opt.input || null;
    this.containerCls = opt.containerCls || 'suggest-container';
    this.itemCls = opt.itemCls || 'suggest-item';
    this.activeCls = opt.activeCls || 'suggest-active';
    this.width = opt.width;
    this.opacity = opt.opacity;
    this.data = opt.data || [];
    this.active = null;
    this.visible = false;
    this.init();
}
InputSuggest.prototype = {
    init: function(){
        this.win = window;
        this.doc = window.document;
        this.container = this.$C('div');
        this.attr(this.container, 'class', this.containerCls);                
        this.doc.body.appendChild(this.container);
        this.setPos();
        var _this = this, input = this.input;        

        this.on(input,'keyup',function(e){
            if(input.value==''){
                _this.hide();
            }else{
                _this.onKeyup(e);
            }
            
        });
        // blur会在click前发生,这里使用mousedown
        this.on(input,'blur',function(e){
            _this.hide();            
        });
        this.onMouseover();
        this.onMousedown();
        
    },
    $C: function(tag){
        return this.doc.createElement(tag);
    },
    getPos: function (el){
        var pos=[0,0], a=el;
        if(el.getBoundingClientRect){
            var box = el.getBoundingClientRect();
            pos=[box.left,box.top];
        }else{
            while(a && a.offsetParent){
                pos[0] += a.offsetLeft;
                pos[1] += a.offsetTop;
                a = a.offsetParent
            }            
        }
        return pos;
    },    
    setPos: function(){
        var input = this.input, 
            pos = this.getPos(input), 
            brow = this.brow, 
            width = this.width,
            opacity = this.opacity,
            container = this.container;
        container.style.cssText =
            'position:absolute;overflow:hidden;left:' 
            + pos[0] + 'px;top:'
            + (pos[1]+input.offsetHeight) + 'px;width:'
            // IE6/7/8/9/Chrome/Safari input[type=text] border默认为2,Firefox为1,因此取offsetWidth-2保证与FF一致
            + (brow.firefox ? input.clientWidth : input.offsetWidth-2) + 'px;';
        if(width){
            container.style.width = width + 'px';
        }
        if(opacity){
            if(this.brow.ie){
                container.style.filter = 'Alpha(Opacity=' + opacity * 100 + ');';
            }else{
                container.style.opacity = (opacity == 1 ? '' : '' + opacity);
            }            
        }
    },
    show: function(){
        this.container.style.visibility = 'visible';
        this.visible = true;
    },
    hide: function(){
        this.container.style.visibility = 'hidden';
        this.visible = false;    
    },
    attr: function(el, name, val){
        if(val === undefined){
            return el.getAttribute(name);
        }else{
            el.setAttribute(name,val);
            name=='class' && (el.className = val);            
        }
    },
    on: function(el, type, fn){
        el.addEventListener ? el.addEventListener(type, fn, false) : el.attachEvent('on' + type, fn);
    },
    un: function(el, type, fn){
        el.removeEventListener ? el.removeEventListener(type, fn, false) : el.detachEvent('on' + type, fn);
    },
    brow: function(ua){
        return {
            ie: /msie/.test(ua) && !/opera/.test(ua),
            opera: /opera/.test(ua),
            firefox: /firefox/.test(ua)
        };
    }(navigator.userAgent.toLowerCase()),
    onKeyup: function(e){
        var container = this.container, input = this.input, iCls = this.itemCls, aCls = this.activeCls;
        if(this.visible){
            switch(e.keyCode){
                case 13: // Enter
                    if(this.active){
                        input.value = this.active.firstChild.data;
                        this.hide();
                    }                    
                    return;
                case 38: // 方向键上
                    if(this.active==null){
                        this.active = container.lastChild;
                        this.attr(this.active, 'class', aCls);
                        input.value = this.active.firstChild.data;
                    }else{
                        if(this.active.previousSibling!=null){
                            this.attr(this.active, 'class', iCls);
                            this.active = this.active.previousSibling;
                            this.attr(this.active, 'class', aCls);
                            input.value = this.active.firstChild.data;
                        }else{
                            this.attr(this.active, 'class', iCls);
                            this.active = null;
                            input.focus();
                            input.value = input.getAttribute("curr_val");
                        }
                    }
                    return;
                case 40: // 方向键下
                    if(this.active==null){
                        this.active = container.firstChild;
                        this.attr(this.active, 'class', aCls);
                        input.value = this.active.firstChild.data;
                    }else{            
                        if(this.active.nextSibling!=null){
                            this.attr(this.active, 'class', iCls);
                            this.active = this.active.nextSibling;
                            this.attr(this.active, 'class', aCls);
                            input.value = this.active.firstChild.data;
                           }else{
                            this.attr(this.active, 'class', iCls);
                            this.active = null;
                            input.focus();
                            input.value = input.getAttribute("curr_val");
                        }
                    }
                    return;

            }
        
        }    
        if(e.keyCode==27){ // ESC键
            this.hide();
            input.value = this.attr(input,'curr_val');
            return;
        }    
        if(input.value.indexOf('@')!=-1){return;}
        this.items = [];
        
        if(this.attr(input,'curr_val')!=input.value){
            this.container.innerHTML = '';
            for(var i=0,len=this.data.length;i<len;i++){
                var item = this.$C('div');
                this.attr(item, 'class', this.itemCls);
                item.innerHTML = input.value + '@' + this.data[i];
                this.items[i] = item;
                this.container.appendChild(item);
            }
            this.attr(input,'curr_val',input.value);        
        }

        this.show();
                    
    },
    onMouseover: function(){
        var _this = this, icls = this.itemCls, acls = this.activeCls;
        this.on(this.container,'mouseover',function(e){
            var target = e.target || e.srcElement;
            if(target.className == icls){
                if(_this.active){
                    _this.active.className = icls;                    
                }
                target.className = acls;
                _this.active = target;

            }
        });
    },
    onMousedown: function(){
        var _this = this;    
        this.on(this.container,'mousedown',function(e){
            var target = e.target || e.srcElement;
            _this.input.value = target.innerHTML;
            _this.hide();
        });
    }
}    

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏菩提树下的杨过

Silverlight:Mouse Avoiding 躲避鼠标效果

昨晚在一国外博客上(从域名后缀pl上猜想应该是波兰)看到这种效果(Mouse Avoid 躲避鼠标),是基于Flash/AS3开发的,这个示例把弹性运动,摩擦力...

23070
来自专栏编程之旅

Swift 宏定义与代码标记

写Objective-C的时候常常会用到各种宏定义,但是Swift中貌似没有宏的这种定义,更多的是通过全局常量或者全局函数来实现这一效果.我们只需要建立一个文件...

41030
来自专栏闵开慧

用JS实现表格中隔行显示不同颜色

用JS实现表格中隔行显示不同颜色  第一种:  <style>  tr{bgColor:expression(      this.b...

342100
来自专栏琯琯博客

JavaScript 103 条技能

1、原生JavaScript实现字符串长度截取 function cutstr(str, len) { var temp; var ic...

29560
来自专栏码农阿宇

利用GDI+在Winfrom绘制验证码

string yzm; private void yangzhengma() { Bitma...

31070
来自专栏前端儿

编写高质量 JavaScript -- 知识点小记

此番改善之后,匿名function里面的变量作用域不再是window,而是局限在函数内。

20710
来自专栏云瓣

从 0 到 1 实现 React 系列 —— 5.PureComponent 实现 && HOC 探幽

本系列文章在实现一个 cpreact 的同时帮助大家理顺 React 框架的核心内容(JSX/虚拟DOM/组件/生命周期/diff算法/setState/Pur...

10510
来自专栏互联网杂技

JavaScript 常用方法总结

经常使用的 JS 方法,今天记下,以便以后查询 /* 手机类型判断 */ var BrowserInfo = { userAgent: navigator.us...

40260
来自专栏谦谦君子修罗刀

贝塞尔曲线之爱琴海 -- 定不负相思意

前言: 一个人有多不正经,就有多深情。一个程序员有多闷,就代表ta有多骚。 我不等山无棱,不等夏雨雪,不等天地合。因为即使江水为竭,即使冬雷震震,我都在你一...

388100
来自专栏web编程技术分享

【H5 音乐播放实例】第五节 音轨制作

15430

扫码关注云+社区

领取腾讯云代金券