时间:2021-07-01 10:21:17 帮助过:32人阅读
1.css代码
#match_email { margin-left:48px; overflow:auto; display:none; width:200px; border:1px solid #aaa; background:#fff; max-height:100px; line-height:20px; } #match_email div { text-decoration:none; color:#000; width:200px; } #match_email div:hover { background:#aaa; } input { height:20px; width:200px; }
在css中将overflow设为auto以及将max-height设为100px表示,在该div高度超多100px就是自动生成滚动条。
2.html代码
<div> 邮箱:<input type="text" name="email" id="email" autocomplete="off" onkeyup="match_mail(this.value)"/> <div id="match_email"></div> </div>
onkeyup时间表示只要手指离开按钮就会触发
3.js代码
<script> //mailBoxs里存储用来匹配的串 var mailBoxs = "@163.com @126.com @129.com" mailBoxs += " @qq.com @vip.qq.com @foxmail.com @live.cn @hotmail.com @sina.com @sina.cn @vip.sina.com"; var matchmail = document.getElementById("match_email"); var email = document.getElementById("email"); function match_mail(keyword) { matchmail.innerHTML = ""; matchmail.style.display = "none"; if (!keyword) return; if (!keyword.match(/^[\w\.\-]+@\w*[\.]?\w*/)) return; keyword = keyword.match(/@\w*[\.]?\w*/); var matchs = mailBoxs.match(new RegExp(keyword+"[^ ]* ","gm")); if (matchs) { matchs = matchs.join("").replace(/ $/,"").split(" "); matchmail.style.display = "block"; for (var i = 0; i < matchs.length; i++) { matchmail.innerHTML += '<div>'+matchs[i]+'</div>'; } } } //点击除了匹配框之外的任何地方,匹配框消失 document.onclick = function(e) { var target = e.target; if (target.id != "matchmail") matchmail.style.display = "none"; } //将匹配框上鼠标所点的字符放入输入框 matchmail.onclick = function(e) { var target = e.target; email.value = email.value.replace(/@.*/,target.innerHTML); } </script>
在js中好几处都用到了正则表达式:
(1)keyword = keyword.match(/@\w*[\.]?\w*/);只获取@后面的内容,包括@;
(2)var matchs = mailBoxs.match(new RegExp(keyword+"[^ ]* ","gm"));进行匹配,把mailBoxs中和keyword匹配的存入matchs中,[^ ]* 指遇到空格不匹配,参数”gm”中'g'指进行全局匹配,'m'指多行匹配;
(3)matchs = matchs.join("").replace(/ $/,"").split(" ");字符串的结尾用空格匹配,$表示字符串的结尾。
在两个匿名函数中,e是在鼠标点击事件发生时系统自动生成的·,e.target是获得鼠标所点的当前对象。