java web在不使用任何插件情况下实现文本框输入自动补全功能

来源:互联网 发布:立邦漆种类 知乎 编辑:程序博客网 时间:2024/06/10 09:43
前台部分:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>word.html</title>        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="this is my page">    <meta http-equiv="content-type" content="text/html; charset=UTF-8"><script type="text/javascript" src="js/jquery.js"></script><script type="text/javascript" src="js/auto.js"></script>  </head>    <body>   suggest:<input id="word" type="text" />   <input type = "button" value="提交" />可以尝试输入大写字母"A、B、T"将有提示      <div id = "auto"> </div>  </body></html>
JS部分:
$(document).ready(function(){//一开始加载方法var highlightindex = -1;///高亮显示的变量值(0-n) 初始-1即无任何 子div 被选中var timeout;///服务器交互延迟var wordInput = $("#word"); //输入框节点var wordInputOffset = wordInput.offset(); //获取输入框的属性函数var autoNode = $("#auto");//初始的auto div节点autoNode.hide();//隐藏autoNode.css("position","absolute"); //相对于其最接近的一个最有定位设置的父对象(wordInput)进行绝对定位autoNode.css("z-index","99");//处于顶层autoNode.css("cursor","default");//鼠标样式autoNode.css("filter","alpha(opacity=50");//透明度autoNode.css("text-overflow","clip");//内容过多时不显示省略标记(...),而是简单的裁切 autoNode.css("border","1px black solid");//边框autoNode.css("top",wordInputOffset.top+wordInput.height()+4+"px");//设置高 以ie8 作为标准autoNode.css("left",wordInputOffset.left-2+"px").width(wordInput.width()+5);//设置左边与宽//当使用到项目中,会发现弹出框的背景色是透明的,需要这里设置一下//autoNode.css("background-color","red");//设置弹出框的背景色    wordInput.blur(function()///失去焦点时促发   {setTimeout(function() //延时200毫秒以便 鼠标的点击事件能执行{ autoNode.hide(); highlightindex = -1;},200);});wordInput.keyup(function(event)//键盘按下{var myEvent = event || window.event; //不同浏览器选不同事件    var keyCode = myEvent.keyCode;//键盘按下的 值        if(keyCode>=48&&keyCode<=57||keyCode >= 65 && keyCode <= 90 || keyCode==8 || keyCode ==46||keyCode==13||keyCode==32)//是英文 或退格或删除键都进与服务器交互    {    var textInput = wordInput.val();//获取输入框的值    if(textInput != "" ) //输入不为空    {    clearTimeout(timeout);//清空前一次的倒数时间    timeout = setTimeout(function(){ //延迟与服务器交互时间提高效率    $.post("servlet/InputServlet",{text:textInput},function(data) //与服务器交互 采用xml返回格式    {    var jqueryObj = $(data);//获取返回值节点    var wordNodes = jqueryObj.find("word"); //找到返回的所有xml-word节点 <word>...</word> 节点可自己在服务端定义    autoNode.html("");//清空内容防止div里面重复    wordNodes.each(function(i)//遍历所有的word节点 变量i从 0-n    {    var wordNode = $(this);//获取当前的word节点     var NewNode = $("<div>").attr("id",i);//新建一个div节点 并给以id属性且等于i值        NewNode.html(wordNode.text()).appendTo(autoNode);//把word节点的内容赋给div节点 并把div追加到(相当于内容插入) autoNode节点的div       NewNode.hover(//鼠标事件    function()//鼠标移到    {    if(highlightindex !=-1)    {//鼠标键盘一起用时防止同时高亮    autoNode.children().eq(highlightindex).css("background-color","white");    }    highlightindex = $(this).attr("id"); //把id值赋给highlightindex    $(this).css("background-color","gray");    },    function(){//鼠标移走    $(this).css("background-color","white");      }    );    NewNode.click(function()//点击鼠标时    {    var clickNode = $(this); //获取当前鼠标节点    wordInput.val(clickNode.text());//赋值给输入框    autoNode.hide();    highlightindex =-1;//....此处可以放点击鼠标选定项时触发的函数    });    });    if(wordNodes.length>0) //有返回值才显示    {    autoNode.show();    }    else//返回为空隐藏    {    autoNode.hide();    }    },"xml");//.post里的方法结束},500);//延时方法结束}    else//输入为空隐藏div节点autoNode 不与服务器交互    {    autoNode.hide();highlightindex = -1;}}else if(keyCode ==38 || keyCode ==40){var autoNodes = autoNode.children();//获取autoNodes div下的所有子节点if(keyCode == 38)//向上{if(highlightindex != -1)//不为-1 原来有节点被选中{autoNodes.eq(highlightindex).css("background-color","white");//改变原来背景色 白色highlightindex--; //减一 向上移到}if(highlightindex == -1){ //为-1 即原来值为0到顶端了highlightindex = autoNodes.length - 1;//直接把变量改为最后一个 (注意长度length是1-n,而highlightindex 0-n)}autoNodes.eq(highlightindex).css("background-color","gray");//改变新选中的div背景色 蓝色wordInput.val(autoNodes.eq(highlightindex).text()); //直接赋值给输入框}if(keyCode == 40)//向下{if(highlightindex!=-1)//不为-1 原来有节点被选中{autoNodes.eq(highlightindex).css("background-color","white");//改变原来选中div背景色 highlightindex++; //加1 即向下移动}if(highlightindex==-1)//为-1及可加     {    highlightindex++;    }       if(highlightindex == autoNodes.length)//加1后等于 子div节点长度到达底端  {highlightindex = 0;//把顶端值赋给highlightindex}autoNodes.eq(highlightindex).css("background-color","gray"); //改变背景色wordInput.val(autoNodes.eq(highlightindex).text()); //直接赋值给输入框}}else if(keyCode==13)//回车{autoNode.hide();//隐藏divhighlightindex = -1;//高亮变量恢复默认值//....................//可作提交操作  }});});
后台部分:
package servlet;import java.io.IOException;import java.util.ArrayList;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class InputServlet extends HttpServlet{    public void doGet(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException    {        request.setCharacterEncoding("utf-8");        String text = request.getParameter("text");//获取页面发来的text变量        System.out.println(text);        List<String> word = new ArrayList<String>();        List<String> list = new ArrayList<String>();//用集合方式存放提示关键字  实际应该从数据库中取        list.add("Google");        list.add("NetEase");        list.add("Sohu");        list.add("Sina");        list.add("Sogou");        list.add("Baidu");        list.add("Tencent");        list.add("Taobao");        list.add("Tom");        list.add("Yahoo");        list.add("JavaEye");        list.add("Csdn");        list.add("Alipay");        for (int i = 0; i < list.size(); i++)//循环对比提示关键字与输入文本        {            if (list.get(i).startsWith(text))//判断输入文本是否与关键字文本开头相同            {                word.add(list.get(i)); //存放到word的集合中            }        }        request.setAttribute("word", word);//放入Request中        request.getRequestDispatcher("/wordxml.jsp").forward(request, response);//跳转到wordxml.jsp    }    public void doPost(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException    {        doGet(request, response);    }}
 资源下载地址:http://download.csdn.net/detail/sunny0703/7690327
0 0
原创粉丝点击