JavaScript實現(xiàn)郵箱地址自動匹配功能代碼
自動匹配技術(shù):簡單的來說就是“根據(jù)用戶輸入的信息來提示一些相似項供用戶選擇”。具有很廣泛的應(yīng)用,比如我們最常用的百度,當輸入一些搜索內(nèi)容后會自動匹配很多相關(guān)信息;再比如我們最常用的輸入法,都是使用這種技術(shù),當然這些都比較難了。下面這個例子是比較簡單的我們常用郵箱的匹配。代碼如下:
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設(shè)為auto以及將max-height設(shè)為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時間表示只要手指離開按鈕就會觸發(fā)
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*/);只獲取@后面的內(nèi)容,包括@;
(2)var matchs = mailBoxs.match(new RegExp(keyword+"[^ ]* ","gm"));進行匹配,把mailBoxs中和keyword匹配的存入matchs中,[^ ]* 指遇到空格不匹配,參數(shù)”gm”中'g'指進行全局匹配,'m'指多行匹配;
(3)matchs = matchs.join("").replace(/ $/,"").split(" ");字符串的結(jié)尾用空格匹配,$表示字符串的結(jié)尾。
在兩個匿名函數(shù)中,e是在鼠標點擊事件發(fā)生時系統(tǒng)自動生成的·,e.target是獲得鼠標所點的當前對象。
最終效果如圖:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
javascript自定義in_array()函數(shù)實現(xiàn)方法
這篇文章主要介紹了javascript自定義in_array()函數(shù)實現(xiàn)方法,涉及javascript數(shù)組的遍歷與查找相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-08-08
JavaScript如何將時間戳轉(zhuǎn)化為年月日時分秒格式
這篇文章主要給大家介紹了關(guān)于JavaScript如何將時間戳轉(zhuǎn)化為年月日時分秒格式的相關(guān)資料,在前端的日常工作當中,時間戳的使用也是不少的,有時后端返回給我們的數(shù)據(jù)是一個時間戳,我們需要轉(zhuǎn)換成年月日,時分秒的形式展示在頁面當中,需要的朋友可以參考下2023-11-11
JavaScript常用進制轉(zhuǎn)換及位運算實例解析
這篇文章主要介紹了JavaScript常用進制轉(zhuǎn)換及位運算實例解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-10-10

