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 相关文章推荐
JQuery的Alert消息框插件使用介绍
Oct 09 Javascript
Js日期选择自动填充到输入框(界面漂亮兼容火狐)
Aug 02 Javascript
使用js的replace()方法查找字符示例代码
Oct 28 Javascript
jquery选择器原理介绍($()使用方法)
Mar 25 Javascript
javascript中innerText和innerHTML属性用法实例分析
May 13 Javascript
JS实现带鼠标效果的头像及文章列表代码
Sep 27 Javascript
基于JavaScript实现在新的tab页打开url
Aug 04 Javascript
12 款 JS 代码测试必备工具(翻译)
Dec 13 Javascript
浅谈实现vue2.0响应式的基本思路
Feb 13 Javascript
微信小程序异步API为Promise简化异步编程的操作方法
Aug 14 Javascript
通过实例解析js简易模块加载器
Jun 17 Javascript
Vue Object 的变化侦测实现代码
Apr 15 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
自动跳转中英文页面
2006/10/09 PHP
PHPExcel读取Excel文件的实现代码
2011/12/06 PHP
PHP基础知识回顾
2012/08/16 PHP
PHP在线生成二维码(google api)的实现代码详解
2013/06/04 PHP
php中eval函数的危害与正确禁用方法
2014/06/30 PHP
PHP实现的限制IP投票程序IP来源分析
2016/05/04 PHP
laravel5.2表单验证,并显示错误信息的实例
2019/09/29 PHP
JavaScript DOM学习第四章 getElementByTagNames
2010/02/19 Javascript
JavaScript创建一个欢迎cookie弹出窗实现代码
2013/03/15 Javascript
jquery ajax属性async(同步异步)示例
2013/11/05 Javascript
js实现的牛顿摆效果
2015/03/31 Javascript
使用Raygun来自动追踪AngularJS中的异常
2015/06/23 Javascript
jQuery中(function($){})(jQuery)详解
2015/07/15 Javascript
javascript断点调试心得分享
2016/04/23 Javascript
Js类的静态方法与实例方法区分及jQuery拓展的两种方法
2016/06/03 Javascript
jQuery选择器总结之常用元素查找方法
2016/08/04 Javascript
vue mint-ui学习笔记之picker的使用
2017/10/11 Javascript
解析Vue 2.5的Diff算法
2017/11/28 Javascript
Vue中render方法的使用详解
2018/01/26 Javascript
详解Webpack-dev-server的proxy用法
2018/09/08 Javascript
解决vue无法设置滚动位置的问题
2018/10/07 Javascript
ES6 Class中实现私有属性的一些方法总结
2019/07/08 Javascript
Windows系统配置python脚本开机启动的3种方法分享
2015/03/10 Python
用Python编写一个简单的Lisp解释器的教程
2015/04/03 Python
Python搜索引擎实现原理和方法
2017/11/27 Python
python经典趣味24点游戏程序设计
2019/07/26 Python
CSS3模拟IOS滑动开关效果
2016/09/28 HTML / CSS
HTML5实现表单自动验证功能实例代码
2017/01/11 HTML / CSS
Room Mate Hotels美国:西班牙酒店品牌
2018/04/10 全球购物
教育技术职业规划范文
2014/03/04 职场文书
化工工艺设计求职信
2014/06/25 职场文书
英文感谢信范文
2015/01/21 职场文书
2016年安全生产先进个人事迹材料
2016/02/29 职场文书
读《方与圆》有感:交友方圆有度
2020/01/14 职场文书
详解python的内存分配机制
2021/05/10 Python
教你使用一行Python代码玩遍童年的小游戏
2021/08/23 Python