自动匹配技术:简单来说就是“根据用户输入的信息提示一些相似的项目供用户选择”。它的应用范围很广,比如最常用的百度。当你输入一些搜索内容时,它会自动匹配很多相关信息;例如,我们最常用的输入法都使用这种技术,这当然很难。以下示例是我们常见邮箱的简单匹配。代码如下:
1.css代码
# match _ email { margin-left :48 px;飞越: auto;display:none宽度width:200pxborder:1px实心# aaa背景# fff最大高度:100 px;线高:20 px;} # match _ email div { text-decoration : none;color: # 000宽度width:200px} # match _ email div : hover { background : # AAA;}输入{ height:20px宽度width:200px}在css中将overflow设置为auto,将max-height设置为100px,这意味着如果div高度超过100px,滚动条将自动生成。
2.html法典
Div邮箱:输入类型=' text ' name=' email ' id=' email ' autocomplete=' off ' onkey up=' match _ mail(this。value)'/div id=' match _ email '/div/div onkey up time表示只要手指离开按钮,它就会触发
3.js代码
script//mailbox存储字符串var mailbox='@163.com @ 126.com @ 129.com ' mailbox=' @ qq.com @ vip.qq.com @ foxmail.com @ live.cn @ hotmail.com @ Sina.com @ Sina . cn @ VIP . Sina . var match mail=document . getelementbyid(' match _ email ');var email=document . getelementbyid(' email ');函数match_mail(关键字){ matchmail.innerHTML=match mail . style . display=' none ';if(!关键字)返回;if(!keyword.match(/^[w.-][emailprotected]w*[。]?w*/))返回;关键字=keyword.match(/@w*[。]? w */);var match=mailbox s . match(new regexp(关键字'[^ ]*、‘GM’);if(matches){ matches=matches . join(')。替换(/$/,' ')。拆分(“”);match mail . style . display=' block ';for(var I=0;我匹配。长度;I){ match mail . innerHTMl=' div ' match[I]'/div ';} } }//点击匹配框以外的任意位置,匹配框消失。document . onclick=function(e){ var target=e . target;if (target.id!=“match mail”)match mail . style . display=“none”;}//将匹配框中鼠标点击的字符放入输入框match mail . onclick=function(e){ var target=e . target;email . value=email . value . replace(/@)。*/,target . innerhtml);}/script在js的几个地方使用了正则表达式:(1)关键字=keyword.match (/@ w * [。]? w */);仅获取@(包括@)之后的内容;(2)var match=mailbox s . match(new regexp(关键字'[^ ]*,' GM '));Match,并将mailBoxs与关键字的匹配存储在match中,[] *表示有空格不匹配,参数“gm”中的g表示全局匹配,m表示多行匹配;(3)matches=matches . join(')。替换(/$/,' ')。拆分(“”);字符串的结尾匹配一个空格,$表示字符串的结尾。
在两个匿名函数中,e是鼠标点击事件发生时系统自动生成的,e.target是获取鼠标点击的当前对象。
最终效果如图所示:
以上就是本文的全部内容。希望对大家的学习有帮助,支持我们。