我們在註冊網站填寫郵箱時,常會看到輸入框會自動彈出 @qq.com、@gmail.com 等常見後綴供選擇,既方便又能減少輸入錯誤。這個「郵箱自動完成」功能可以用 JavaScript 搭配 jQuery 輕鬆實現。
以下是完整代碼,保存成 html 文件打開即可:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>輸入用戶名自動顯示郵箱後綴列表-</title>
<script type="text/javascript" src="https:///keleyi/pmedia/jquery/jquery-1.10.2.min.js"></script>
<style>
*{margin:0;padding:0;}
ul,li{list-style:none;}
.inputElem {width:198px;height:22px;line-height:22px;border:1px solid #ff4455;}
.parentCls{width:200px;}
.auto-tip li{width:100%;height:22px;line-height:22px;font-size:14px;}
.auto-tip li.hoverBg{background:#ddd;cursor:pointer;}
.red{color:red;}
.hidden {display:none;}
</style>
<script type="text/javascript" src="https:///keleyi/phtml/jstexiao/7/emailAutoComplete.js"></script>
</head>
<body>
<div style="width:736px;margin:10px auto;">
<div><h2>輸入用戶名自動顯示郵箱後綴列表·</h2><a href="https:///a/bjac/xvcdrv0w.htm" target="_blank">原文</a></div>
請在下方輸入郵箱用戶名:
<div class="parentCls">
<input type="text" class="inputElem">
</div>
</div>
</body>
</html>
原理:頁面中有一個輸入框,當使用者輸入任何字時,會自動下拉顯示對應的郵箱後綴提示。例如在輸入框輸入 11 時,下拉框會顯示所有 @ 後綴的郵箱;輸入其他內容時,則給出對應的提示。
結構設計:這個插件不需要額外的 HTML 標籤,只需一個帶特定 class 的輸入框即可,其餘的 HTML 都由腳本自動生成。最小結構如下:
<div class="parentCls"> <input type="text" class="inputElem"> </div>
之所以需要一個父級 class,是因為頁面上可能有多個輸入框,用它來區分是哪一個;同時還會有一個隱藏域用來存值給後台。郵箱列表透過配置項的 mailArr 參數定義,例如 ["@qq.com","@gmail.com","@126.com","@163.com",...],可依需求自訂。
實現的功能:
整體效果與我們熟悉的網頁註冊郵箱自動提示如出一轍,能顯著提升填寫效率與使用者體驗。