JS实现的一个简单的Autocomplete自动完成例子


Posted in Javascript onApril 16, 2014

分享一篇无意间发现的自动完成源码。这里测试的时候使用的是数组,实际使用的时候,我们换成Ajax从服务器端获取的方式就OK了。

提示:可以直接保存到一个html文件中查看效果。

<!doctype html>
<html>
<style>
body {
    margin-left: 0px;
    margin-top: 0px;
    margin-right: 0px;
    margin-bottom: 0px;
}
.auto_hidden {
    width:204px;border-top: 1px solid #333;
    border-bottom: 1px solid #333;
    border-left: 1px solid #333;
    border-right: 1px solid #333;
    position:absolute;
    display:none;
}
.auto_show {
    width:204px;
    border-top: 1px solid #333;
    border-bottom: 1px solid #333;
    border-left: 1px solid #333;
    border-right: 1px solid #333;
    position:absolute;
    z-index:9999; /* 设置对象的层叠顺序 */
    display:block;
}
.auto_onmouseover{
    color:#ffffff;
    background-color:highlight;
    width:100%;
}
.auto_onmouseout{
    color:#000000;
    width:100%;
    background-color:#ffffff;
}
</style>
<script language="javascript">
<!--
var $ = function (id) {
    return "string" == typeof id ? document.getElementById(id) : id;
}
var Bind = function(object, fun) {
    return function() {
        return fun.apply(object, arguments);
    }
}
function AutoComplete(obj,autoObj,arr){
    this.obj=$(obj);        //输入框
    this.autoObj=$(autoObj);//DIV的根节点
    this.value_arr=arr;        //不要包含重复值
    this.index=-1;          //当前选中的DIV的索引
    this.search_value="";   //保存当前搜索的字符
}
AutoComplete.prototype={
    //初始化DIV的位置
    init: function(){
        this.autoObj.style.left = this.obj.offsetLeft + "px";
        this.autoObj.style.top  = this.obj.offsetTop + this.obj.offsetHeight + "px";
        this.autoObj.style.width= this.obj.offsetWidth - 2 + "px";//减去边框的长度2px  
    },
    //删除自动完成需要的所有DIV
    deleteDIV: function(){
        while(this.autoObj.hasChildNodes()){
            this.autoObj.removeChild(this.autoObj.firstChild);
        }
        this.autoObj.className="auto_hidden";
    },
    //设置值
    setValue: function(_this){
        return function(){
            _this.obj.value=this.seq;
            _this.autoObj.className="auto_hidden";
        }      
    },
    //模拟鼠标移动至DIV时,DIV高亮
    autoOnmouseover: function(_this,_div_index){
        return function(){
            _this.index=_div_index;
            var length = _this.autoObj.children.length;
            for(var j=0;j<length;j++){
                if(j!=_this.index ){      
                    _this.autoObj.childNodes[j].className='auto_onmouseout';
                }else{
                    _this.autoObj.childNodes[j].className='auto_onmouseover';
                }
            }
        }
    },
    //更改classname
    changeClassname: function(length){
        for(var i=0;i<length;i++){
            if(i!=this.index ){      
                this.autoObj.childNodes[i].className='auto_onmouseout';
            }else{
                this.autoObj.childNodes[i].className='auto_onmouseover';
                this.obj.value=this.autoObj.childNodes[i].seq;
            }
        }
    }
    ,
    //响应键盘
    pressKey: function(event){
        var length = this.autoObj.children.length;
        //光标键"↓"
        if(event.keyCode==40){
            ++this.index;
            if(this.index>length){
                this.index=0;
            }else if(this.index==length){
                this.obj.value=this.search_value;
            }
            this.changeClassname(length);
        }
        //光标键"↑"
        else if(event.keyCode==38){
            this.index--;
            if(this.index<-1){
                this.index=length - 1;
            }else if(this.index==-1){
                this.obj.value=this.search_value;
            }
            this.changeClassname(length);
        }
        //回车键
        else if(event.keyCode==13){
            this.autoObj.className="auto_hidden";
            this.index=-1;
        }else{
            this.index=-1;
        }
    },
    //程序入口
    start: function(event){
        if(event.keyCode!=13&&event.keyCode!=38&&event.keyCode!=40){
            this.init();
            this.deleteDIV();
            this.search_value=this.obj.value;
            var valueArr=this.value_arr;
            valueArr.sort();
            if(this.obj.value.replace(/(^\s*)|(\s*$)/g,'')==""){ return; }//值为空,退出
            try{ var reg = new RegExp("(" + this.obj.value + ")","i");}
            catch (e){ return; }
            var div_index=0;//记录创建的DIV的索引
            for(var i=0;i<valueArr.length;i++){
                if(reg.test(valueArr[i])){
                    var div = document.createElement("div");
                    div.className="auto_onmouseout";
                    div.seq=valueArr[i];
                    div.onclick=this.setValue(this);
                    div.onmouseover=this.autoOnmouseover(this,div_index);
                    div.innerHTML=valueArr[i].replace(reg,"<strong>$1</strong>");//搜索到的字符粗体显示
                    this.autoObj.appendChild(div);
                    this.autoObj.className="auto_show";
                    div_index++;
                }
            }
        }
        this.pressKey(event);
        window.onresize=Bind(this,function(){this.init();});
    }
}
//-->
</SCRIPT>
<body>
<h1 align="center">自动完成函数(Autocomplete Function)</h1>
    <div align="center"><input type="text" style="width:300px;height:20px;font-size:14pt;" id="o" onkeyup="autoComplete.start(event)"></div>
    <div class="auto_hidden" id="auto"><!--自动完成 DIV--></div>
<script>
    var autoComplete=new AutoComplete('o','auto',['b0','b12','b22','b3','b4','b5','b6','b7','b8','b2','abd','ab','acd','accd','b1','cd','ccd','cbcv','cxf']);
</SCRIPT>
</body>
</html>

Javascript 相关文章推荐
JavaScript 监听textarea中按键事件
Oct 08 Javascript
禁止选中文字兼容IE、Chrome、FF等
Sep 04 Javascript
javascript实现控制浏览器全屏
Mar 30 Javascript
node.js+express制作网页计算器
Jan 17 Javascript
JavaScript模版引擎的基本实现方法浅析
Feb 15 Javascript
jquery div模态窗口的简单实例
May 28 Javascript
Bootstrap编写一个兼容主流浏览器的受众巨幕式风格页面
Jul 01 Javascript
Vue.js实现一个漂亮、灵活、可复用的提示组件示例
Mar 17 Javascript
微信、QQ、微博、Safari中使用js唤起App
Jan 24 Javascript
vue+elementUi图片上传组件使用详解
Aug 20 Javascript
React中获取数据的3种方法及优缺点
Feb 18 Javascript
vscode 配置vue+vetur+eslint+prettier自动格式化功能
Mar 23 Javascript
JavaScript中一个奇葩的IE浏览器判断方法
Apr 16 #Javascript
JavaScript面向对象编程入门教程
Apr 16 #Javascript
jQuery的cookie插件实现保存用户登陆信息
Apr 15 #Javascript
jquery实现点击文字可编辑并修改保存至数据库
Apr 15 #Javascript
jQuery制作的别致导航有阴影背景高亮模式窗口
Apr 15 #Javascript
JS比较2个日期间隔的示例代码
Apr 15 #Javascript
模拟一个类似百度google的模糊搜索下拉列表
Apr 15 #Javascript
You might like
mysql 性能的检查和优化方法
2009/06/21 PHP
PHP中改变图片的尺寸大小的代码
2011/07/17 PHP
微信支付开发教程(一)微信支付URL配置
2014/05/28 PHP
PHP中array_slice函数用法实例详解
2014/11/25 PHP
php去除字符串中空字符的常用方法小结
2015/03/17 PHP
Yii框架日志记录Logging操作示例
2018/07/12 PHP
Firefox下提示illegal character并出现乱码的原因
2010/03/25 Javascript
jquery.validate使用攻略 第一部
2010/07/01 Javascript
使用ExtJS技术实现的拖动树结点
2010/08/05 Javascript
基于jquery实现的文字向上跑动类似跑马灯的效果
2014/06/17 Javascript
html+js实现简单的计算器代码(加减乘除)
2016/07/12 Javascript
原生js仿淘宝网商品放大镜效果
2017/02/28 Javascript
Mongoose中document与object的区别示例详解
2017/09/18 Javascript
从零开始最小实现react服务器渲染详解
2018/01/26 Javascript
vue input输入框模糊查询的示例代码
2018/05/22 Javascript
小程序兼容安卓和IOS数据处理问题及坑
2018/09/18 Javascript
微信小程序实现日历效果
2018/12/28 Javascript
原生JS实现音乐播放器的示例代码
2021/02/25 Javascript
Python中的exec、eval使用实例
2014/09/23 Python
mac PyCharm添加Python解释器及添加package路径的方法
2018/10/29 Python
python 返回列表中某个值的索引方法
2018/11/07 Python
python输入整条数据分割存入数组的方法
2018/11/13 Python
Python中fnmatch模块的使用详情
2018/11/30 Python
Python实现Restful API的例子
2019/08/31 Python
Python小白垃圾回收机制入门
2020/06/09 Python
CSS3 滤镜 webkit-filter详细介绍及使用方法
2012/12/27 HTML / CSS
英国最受欢迎的手表网站:Watch Shop
2016/10/21 全球购物
澳大利亚百货商店中销量第一的商务衬衫品牌:Van Heusen
2018/07/26 全球购物
英国鹦鹉店:Parrot Essentials
2018/12/03 全球购物
编写类String 的构造函数、析构函数和赋值函数
2012/09/09 面试题
药学专业大学生个人的自我评价
2013/11/04 职场文书
yy生日主持词
2014/03/20 职场文书
个人借款担保书
2014/04/02 职场文书
仙境之桥观后感
2015/06/16 职场文书
天气温馨提示语
2015/07/14 职场文书
Mac环境Nginx配置和访问本地静态资源的实现
2021/03/31 Servers