HTML5 datalist与动态邮箱地址实例

时间:2021-01-05 19:17:14
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
邮箱:<input type="email" id="email" list="emailList" name="off_autocomplete" />
<datalist id="emailList">
<option value="*@qq.com">
<option value="*@163.com">
<option value="*@gmail.com">
<option value="*@yahoo.com.cn">
<option value="*@126.com">
</datalist>

<script>
var eleList = document.getElementById("emailList")
, eleMail = document.getElementById("email")
, htmlListInit = '', arrEmailList = [];

if (eleMail && eleList && (htmlListInit = eleList.innerHTML) !== '') {
// 得到类似["qq.com", "163.com", "gmail.com", ...]的数据
arrEmailList = [].slice.call(eleList.getElementsByTagName("option")).map(function(option) {
return option.value.replace("*@", "");
});

eleMail.fnListReplace = function() {
var arrValue = this.value.trim().split("@");
// 修复FireFox浏览器下无限input问题
// 如果值不完全匹配某option值,执行动态替换
if (arrValue.length !== 2 || arrEmailList.indexOf(arrValue[1]) === -1) {
eleList.innerHTML = htmlListInit.replace(/\*/g, arrValue[0]);
}
return this;
};
// 绑定输入事件侦听
eleMail.addEventListener("input", function() {
this.fnListReplace.call(this);
}, false);

// 载入即匹配
eleMail.fnListReplace.call(eleMail).focus();
} else {
eleList = document.createElement("datalist");
eleList.innerHTML = '<p class=sorry>抱歉,当前浏览器不支持HTML5 datalist.</p>';
eleMail.parentNode.appendChild(eleList);
}
</script>
</body>


</html>