外掛功能
- 輸入 @ 前字元時,下拉顯示常見郵箱域名建議
- 鍵盤 ↑↓ 選擇、Enter 確認填入
- 滑鼠點選填入
- 點擊文件其他處關閉下拉
- 可自訂域名清單、樣式類別
外掛結構
(function($) {
$.fn.autoMail = function(options) {
var $input = $(this);
var opts = $.extend({}, $.fn.autoMail.defaults, options);
var $list, index = -1;
// 初始化
$input.val(opts.deValue).addClass(opts.textCls)
.on("click", function(e) {
$(this).select().removeClass(opts.textCls);
if ($(this).val() !== opts.deValue) showList();
e.stopPropagation();
})
.on("blur", function() {
if (!$(this).val() || $(this).val() === opts.deValue) {
$(this).val(opts.deValue).addClass(opts.textCls);
}
})
.on("keyup", function(e) {
handleKeys(e);
});
$(document).on("click", function() { hideList(); });
function showList() {
if (!$list) {
$list = $("").addClass(opts.listCls).css({
position: "absolute",
left: $input.offset().left,
top: $input.offset().top + $input.outerHeight() + opts.listTop,
width: $input.outerWidth(),
zIndex: 9999,
background: "white",
border: "1px solid #ccc",
listStyle: "none",
padding: 0, margin: 0
}).appendTo("body");
}
$list.empty();
var val = $input.val();
var at = val.indexOf("@");
var prefix = at > 0 ? val.substring(0, at) : val;
opts.mailArr.forEach(function(domain) {
$("- ").addClass("item").text(prefix + "@" + domain)
.css({padding: "5px 10px", cursor: "pointer"})
.hover(function() { $(this).addClass("select").siblings().removeClass("select"); })
.click(function() {
$input.val($(this).text()).removeClass(opts.textCls);
hideList();
})
.appendTo($list);
});
$list.show();
index = -1;
}
function hideList() { if ($list) $list.hide(); }
function handleKeys(e) {
var key = e.which;
var $items = $list ? $list.find(".item") : $();
if (key === 13) { // Enter
if ($items.length && index >= 0) $items.eq(index).click();
hideList(); $input.blur();
} else if (key === 38) { // Up
index = Math.max(0, index - 1); highlight();
} else if (key === 40) { // Down
index = Math.min($items.length - 1, index + 1); highlight();
} else if (val.indexOf("@") < 0) {
showList();
}
}
function highlight() {
$list.find(".item").removeClass("select").eq(index).addClass("select");
}
};
$.fn.autoMail.defaults = {
deValue: "請輸入郵箱地址",
textCls: "text-gray",
listCls: "list-mail",
listTop: 1,
mailArr: ["qq.com","gmail.com","126.com","163.com","hotmail.com","yahoo.com","yahoo.com.cn","live.com","sohu.com","sina.com"]
};
})(jQuery);
使用方式
<input type="text" id="email" />
<script>
$("#email").autoMail({
mailArr: ["company.com", "gmail.com", "yahoo.com"] // 自訂域名
});
</script>
CSS 樣式建議
.text-gray { color: #999; }
.list-mail .item.select { background: #007bff; color: white; }