`

自动提示js代码示例

 
阅读更多
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>autoComplete</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
.autoComplete {margin:8px;position:relative;float:left;}
.autoComplete input {width:200px;height:25px;margin:0;padding:0;line-height:25px;}
.autoComplete ul {z-index:-12;padding:0px;margin:0px;border:1px #333 solid;width:200px;background:white;display:none;position:absolute;left:0;top:28px;*margin-left:9px;*margin-top:2px;margin-top:1px\0;}
.autoComplete li {list-style:none;}
.autoComplete li a {display:block;color:#000;text-decoration:none;padding:1px 0 1px 5px;_width:97%;}
.autoComplete li a:hover {color:#000;background:#ccc;border:none;}
</style>
<script type="text/javascript">
//<![CDATA[
var getElementsByClassName = function (searchClass, node, tag) {/* 兼容各浏览器的选择class的方法;(写法参考了博客园:http://www.cnblogs.com/rubylouvre/archive/2009/07/24/1529640.html,想了解更多请看这个地址) */
    node = node || document, tag = tag ? tag.toUpperCase() : "*";
    if(document.getElementsByClassName){/* 支持getElementsByClassName的浏览器 */
        var temp = node.getElementsByClassName(searchClass);
        if(tag=="*"){
            return temp;
        } else {
            var ret = new Array();
            for(var i=0; i<temp.length; i++)
                if(temp[i].nodeName==tag)
                    ret.push(temp[i]);
            return ret;
        }
    }else{/* 不支持getElementsByClassName的浏览器 */
        var classes = searchClass.split(" "),
            elements = (tag === "*" && node.all)? node.all : node.getElementsByTagName(tag),
            patterns = [], returnElements = [], current, match;
        var i = classes.length;
        while(--i >= 0)
            patterns.push(new RegExp("(^|\\s)" + classes[i] + "(\\s|$)"));
        var j = elements.length;
        while(--j >= 0){
            current = elements[j], match = false;
            for(var k=0, kl=patterns.length; k<kl; k++){
                match = patterns[k].test(current.className);
                if(!match) break;
            }
            if(match) returnElements.push(current);
        }
        return returnElements;
    }
};
var addEvent=(function(){/* 用此函数添加事件防止事件覆盖 */
    if(document.addEventListener){
        return function(type, fn){ this.addEventListener(type, fn, false); };
    }else if(document.attachEvent){
        return function(type,fn){
            this.attachEvent('on'+type, function () {
                return fn.call(this, window.event);/* 兼容IE */
            });
        };
    }
})();
;(function(window){
/* 插件开始 */
var autoComplete=function(o){
    var handler=(function(){
        var handler=function(e,o){ return new handler.prototype.init(e,o); };/* 为每个选择的dom都创建一个相对应的对象,这样选择多个dom时可以很方便地使用 */
        handler.prototype={
            e:null, o:null, timer:null, show:0, input:null, popup:null,
            init:function(e,o){/* 设置初始对象 */
                this.e=e, this.o=o,
                this.input=this.e.getElementsByTagName(this.o.input)[0],
                this.popup=this.e.getElementsByTagName(this.o.popup)[0],
                this.initEvent();/* 初始化各种事件 */
            },
            match:function(quickExpr,value,source){/* 生成提示 */
                var li = null;
                for(var i in source){
                    if( value.length>0 && quickExpr.exec(source[i])!=null ){
                        li = document.createElement('li');
                        li.innerHTML = '<a href="javascript:;">'+source[i]+'</a>';
                        this.popup.appendChild(li);
                    }
                }
                if(this.popup.getElementsByTagName('a').length)
                    this.popup.style.display='block';
                else
                    this.popup.style.display='none';
            },
            ajax:function(type,url,quickExpr,search){/* ajax请求远程数据 */
                var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
                xhr.open(type,url,true);/* 同异步在此修改 */
                xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
                var that=this;
                xhr.onreadystatechange = function(){
                    if(xhr.readyState==4) {
                        if(xhr.status==200) {
                            var data = eval(xhr.responseText);
                            that.match(quickExpr,search,data);/* 相同于成功的回调函数 */
                        }else{
                            alert("请求页面异常!");/* 请求失败 */
                        }
                    }
                };
                xhr.send(null);
            },
            fetch:function(ajax,search,quickExpr){
                var that=this;
                this.ajax(ajax.type,ajax.url+search,quickExpr,search);
            },
            initEvent:function(){/* 各事件的集合 */
                var that=this;
                this.input.onfocus = function(){
                    if(this.inputValue) this.value = this.inputValue;
                    var value=this.value, quickExpr=RegExp('^'+value,'i'), self=this;
                    var els = that.popup.getElementsByTagName('a');
                    if(els.length>0) that.popup.style.display = 'block';
                    that.timer=setInterval(function(){
                        if(value!=self.value){/* 判断输入内容是否改变,兼容中文 */
                            value=self.value;
                            that.popup.innerHTML='';
                            if(value!=''){
                                quickExpr=RegExp('^'+value);
                                if(that.o.source) that.match(quickExpr,value,that.o.source);
                                else if(that.o.ajax) that.fetch(that.o.ajax,value,quickExpr);
                            }
                        }
                    },200);
                };
                this.input.onblur = function(){/*  输入框添加事件 */
                    if(this.value!=this.defaultValue) this.inputValue = this.value;
                    clearInterval(that.timer);
                    var current=-1;/* 记住当前有焦点的选项 */
                    var els = that.popup.getElementsByTagName('a');
                    var len = els.length-1;
                    var aClick = function(){
                        that.input.inputValue = this.firstChild.nodeValue;
                        that.popup.innerHTML='';
                        that.popup.style.display='none';
                        that.input.focus();
                    };
                    var aFocus = function(){
                        for(var i=len; i>=0; i--){
                            if(this.parentNode===that.popup.children[i]){
                                current = i;
                                break;
                            }
                        }
                        //that.input.value = this.firstChild.nodeValue;
                        for(var k in that.o.elemCSS.focus){
                            this.style[k] = that.o.elemCSS.focus[k];
                        }
                    };
                    var aBlur= function(){
                        for(var k in that.o.elemCSS.blur)
                            this.style[k] = that.o.elemCSS.blur[k];
                    };
                    var aKeydown = function(event){
                        event = event || window.event;/* 兼容IE */
                        if(current === len && event.keyCode===9){/* tab键时popup隐藏 */
                            that.popup.style.display = 'none';
                        }else if(event.keyCode==40){/* 处理上下方向键事件方便选择提示的选项 */
                            current++;
                            if(current<-1) current=len;
                            if(current>len){
                                current=-1;
                                that.input.focus();
                            }else{
                                that.popup.getElementsByTagName('a')[current].focus();
                            }
                        }else if(event.keyCode==38){
                            current--;
                            if(current==-1){
                                that.input.focus();
                            }else if(current<-1){
                                current = len;
                                that.popup.getElementsByTagName('a')[current].focus();
                            }else{
                                that.popup.getElementsByTagName('a')[current].focus();
                            }
                        }
                    };
                    for(var i=0; i<els.length; i++){/* 为每个选项添加事件 */
                        els[i].onclick = aClick;
                        els[i].onfocus = aFocus;
                        els[i].onblur = aBlur;
                        els[i].onkeydown = aKeydown;
                    }
                };
                this.input.onkeydown = function(event){
                    event = event || window.event;/* 兼容IE */
                    var els = that.popup.getElementsByTagName('a');
                    if(event.keyCode==40){
                        if(els[0]) els[0].focus();
                    }else if(event.keyCode==38){
                        if(els[els.length-1]) els[els.length-1].focus();
                    }else if(event.keyCode==9){
                        if(event.shiftKey==true) that.popup.style.display = 'none';
                    }
                };
                this.e.onmouseover = function(){ that.show=1; };
                this.e.onmouseout = function(){ that.show=0; };
                addEvent.call(document,'click',function(){
                    if(that.show==0){
                        that.popup.style.display='none';
                    }
                });/* 处理提示框dom元素不支持onblur的情况 */
            }
        };
        handler.prototype.init.prototype=handler.prototype;/* JQuery style,这样我们在处的时候就不用每个dom元素都用new来创建对象了 */
        return handler;/* 把内部的处理函数传到外部 */
    })();
    if(this.length){/* 处理选择多个dom元素 */
        for(var a=this.length-1; a>=0; a--){/* 调用方法为每个选择的dom生成一个处理对象,使它们不互相影响 */
            handler(this[a],o);
        }
    }else{/* 处理选择一个dom元素 */
        handler(this,o);
    }
    return this;
};
return window.autoComplete = autoComplete;/* 暴露方法给全局对象 */
/* 插件结束 */
})(window);
/* 调用 */
addEvent.call(null,'load',function(){
    autoComplete.call( getElementsByClassName('autoComplete'), {/* 使用call或apply调用此方法 */
            source:['0123','023',123,1234,212,214,'033333','0352342',1987,17563,20932],/* 提示时在此数组中搜索 */
            //ajax:{ type:'post',url:'./php/fetch.php?search=' },/* 如果使用ajax则远程返回的数据格式要与source相同 */
            elemCSS:{ focus:{'color':'black','background':'#ccc'}, blur:{'color':'black','background':'transparent'} },/* 些对象中的key要js对象中的style属性支持 */
            input:'input',/* 输入框使用input元素 */
            popup:'ul'/* 提示框使用ul元素 */
    });
});
//]]>
</script>
	</head>
    <body><!-- 这所以使用这么多的z-index是因为ie6和ie7的问题 -->
        <div>
        <div class="autoComplete" style="z-index:19"> <input value="input" /> <ul><li></li></ul> </div>
		<!--<div class="autoComplete" style="z-index:18"> <input value="input" /> <ul><li></li></ul> </div>
        <div class="autoComplete" style="z-index:17"> <input value="input" /> <ul><li></li></ul> </div>
        <div class="autoComplete" style="z-index:16"> <input value="input" /> <ul><li></li></ul> </div>
        <div class="autoComplete" style="z-index:15"> <input value="input" /> <ul><li></li></ul> </div>
        <div class="autoComplete" style="z-index:14"> <input value="input" /> <ul><li></li></ul> </div>
        <div class="autoComplete" style="z-index:13"> <input value="input" /> <ul><li></li></ul> </div>
        <div class="autoComplete" style="z-index:12"> <input value="input" /> <ul><li></li></ul> </div>
        <div class="autoComplete" style="z-index:11"> <input value="input" /> <ul><li></li></ul> </div>
        <div class="autoComplete" style="z-index:10"> <input value="input" /> <ul><li></li></ul> </div>
        <div class="autoComplete" style="z-index:9"> <input value="input" /> <ul><li></li></ul> </div>
        <div class="autoComplete" style="z-index:8"> <input value="input" /> <ul><li></li></ul> </div>
        <div class="autoComplete" style="z-index:7"> <input value="input" /> <ul><li></li></ul> </div>
        <div class="autoComplete" style="z-index:6"> <input value="input" /> <ul><li></li></ul> </div>
        <div class="autoComplete" style="z-index:5"> <input value="input" /> <ul><li></li></ul> </div>
        <div class="autoComplete" style="z-index:4"> <input value="input" /> <ul><li></li></ul> </div>
        <div class="autoComplete" style="z-index:3"> <input value="input" /> <ul><li></li></ul> </div>
        <div class="autoComplete" style="z-index:2"> <input value="input" /> <ul><li></li></ul> </div>
        <div class="autoComplete" style="z-index:1"> <input value="input" /> <ul><li></li></ul> </div>
        <div class="autoComplete" style="z-index:0"> <input value="input" /> <ul><li></li></ul> </div> -->
        
        <div style="clear:both;"></div>
        </div>
        <div style="border:3px red double;margin:15px;padding:5px;">
            <h3 style="line-height:10px;">Tip:</h3>
            <ul>
                <li>输入0、1,2会得到提示。</li>
                <li>用鼠标或上下键可以选择提示。</li>
                <li>选择点击鼠标或点回车可以选择选项。</li>
                <li>可以修改调用处,使各个输入框提示不同内容。</li>
            </ul>
        </div>
	</body>
</html>
分享到:
评论

相关推荐

    js自动补全功能

    在创建交互式用户界面时,JS输入框的自动提示补全功能是提高用户体验的重要工具。这个功能通常应用于搜索框、表单输入和其他需要用户输入数据的场景,能帮助用户快速找到或输入他们想要的内容。 实现JS输入框自动...

    Ajax搜索自动提示示例js

    Ajax搜索自动提示示例js代码简略点拨。

    JS自动补全下拉框代码

    JavaScript自动补全功能,也称为智能提示或自动完成,是一种常见的前端交互设计,常用于搜索引擎、表单输入等场景,以提升用户体验。本代码示例实现了基础的自动补全功能,但AJAX部分需要开发者自行添加。以下是关于...

    openLayers完整代码示例数据

    OpenLayers 是一个开源JavaScript库,专门用于在网页上创建交互式...在实际应用中,开发人员需要结合JSON数据的结构和OpenLayers API,编写JavaScript代码来构建地图应用,实现数据的动态加载、渲染以及与用户的交互。

    js邮箱提示功能 可以自己添加

    "表明这个功能是一个可下载、可运行的JavaScript代码示例。用户可以将代码下载到本地,然后在自己的环境中进行测试和调试。这通常意味着代码包含了一个简单的实现,可能是一个独立的JavaScript文件和一个HTML文件,...

    文本框输入 @ 符号的输入提示的JS代码.rar

    总的来说,这个JS代码示例涵盖了JavaScript事件处理、字符串操作、DOM操作、可能的Ajax请求以及用户体验设计等多个核心概念。开发者可以在此基础上进行定制,以适应不同的应用场景,例如添加缓存机制、优化搜索算法...

    EXTJS 折线 chart action 代码示例

    本篇文章将深入探讨EXTJS折线chart与action交互的代码示例,以及如何通过远程和本地加载数据。 首先,让我们了解EXTJS折线chart的基本结构。创建一个折线图通常涉及到以下几个步骤: 1. 定义store:存储图表所需的...

    js自动提示邮箱

    在JavaScript和jQuery的世界里,"js自动提示邮箱"是一个常见的功能,它涉及到用户输入时的实时验证和自动补全。这种技术通常用于提高用户体验,帮助用户更快、更准确地输入邮箱地址,避免输入错误。本篇文章将深入...

    JS点击按钮自动倒计时代码.zip

    在这个名为"JS点击按钮自动倒计时代码.zip"的压缩包中,可能包含两个示例,分别对应这两种应用场景。 首先,我们来看第一个示例——“阅读条款后激活按钮”。这种设计通常出现在用户注册或登录的过程中,要求用户在...

    Ajax做的一个自动提示的小示例

    这个标题提到的“Ajax做的一个自动提示的小示例”是一个使用Ajax实现的交互功能,通常用于输入框,当用户输入特定字符时,系统会根据输入内容实时提供下拉建议,提升用户体验。 在描述中提到了...

    搜索自动提示例子(源代码)

    这个压缩包文件的标题是“搜索自动提示例子(源代码)”,表明其中包含了一个实现搜索自动提示功能的源代码示例。描述提到“类似于百度搜索,自动生成下拉选项,节省资源”,这暗示了该示例可能采用了类似百度搜索...

    javascript经典效果示例

    49:___按比例缩放图片,JavaScript代码 50:___最简的JavaScript鼠标经过切换图片 51:___有点炫的JavaScript立体图片展示 52:___根据鼠标放上切换内容制作的图片导航 53:___浮动的图片广告 54:___清爽简洁的图片交替...

    代码高亮显示javascript插件

    CodeMirror是一个流行的开源代码编辑器组件,广泛应用于在线编辑器、代码示例和教程网站。CodeMirror-2.22是其早期的一个版本,尽管如此,它依然提供了丰富的功能: 1. 多语言支持:CodeMirror不仅支持JavaScript,...

    Ajax实现自动提示源代码

    **三、JavaScript代码示例** ```javascript // 创建XMLHttpRequest对象 var xhr = new XMLHttpRequest(); // 监听输入框的keyup事件 document.getElementById('inputBox').addEventListener('keyup', function...

    JavaScript编辑器有提示

    3. 学习辅助:对于初学者来说,编辑器的提示功能可以提供代码示例,帮助理解各种函数和API的用法。 二、JavaScript编辑器的类型 1. 基础文本编辑器:如Notepad++、Sublime Text等,虽然功能相对简单,但通过安装...

    Gridview各种高级用法汇总(含代码示例)

    - 使用JavaScript或jQuery添加确认提示。 8. **自动编号**: - 可通过自定义模板列,结合RowDataBound事件实现。 9. **自定义时间货币等字符串格式**: - 使用DataFormatString属性,如`DataFormatString="{0:...

    JS实现自动提示文本框

    这个简单的示例展示了如何使用JavaScript实现自动提示文本框的基本功能。在实际应用中,你可能需要考虑更多细节,比如异步加载数据源、输入过滤规则、多个匹配项高亮等。通过不断优化和扩展,可以创建出更智能、更...

    JS自动获取公司位置地址代码.zip

    本项目提供的"JS自动获取公司位置地址代码.zip"包含了一套原生JavaScript代码,用于实现用户在地图上选择公司位置后,系统能够自动生成并显示相应的详细地址。下面我们将深入探讨这一技术的实现原理和相关知识点。 ...

    C# 动态自动补全功能 含css js 和前后台代码

    2. JavaScript代码:可能是一个前端自动补全库,如Autocomplete.js或与特定框架(如React、Vue等)的集成组件。 3. CSS样式表:可能为自动补全框提供定制的样式,如颜色、大小和动画效果。 4. HTML模板:用于构建...

Global site tag (gtag.js) - Google Analytics