引自:input输入中文时,拼音在输入框内会触发input事件的问题。
话不多说,代码贴上。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="../js/jquery-3.3.1.min.js"></script>
<title></title>
<style>
* {
padding: 0;
margin: 0;
list-style: none;
}
.center-div {
position: absolute;
left: 50%;
margin-left: -150px;
margin-top: 200px;
width: 300px;
}
input {
width: 300px;
height: 40px;
padding-left: 10px;
outline: none;
border: 1px solid #999;
border-radius: 4px;
}
#result-list {
position: absolute;
top: 45px;
width: 310px;
border: 1px solid #999;
border-radius: 4px;
}
#result-list li {
width: 300px;
height: 35px;
font-size: 14px;
line-height: 35px;
padding-left: 10px;
text-align: left;
border-bottom: 1px solid #ededed;
cursor: pointer;
}
#result-list li:hover {
background: #F2F4F8;
}
.hide {
display: none;
}
</style>
</head>
<body>
<div class="center-div">
<input id="txt" type="text" placeholder="请输入关键词">
<ul id="result-list" class="hide"></ul>
</div>
<script>
var flag = true;
var test_list = ["小张", "小苏", "小杨", "老张", "老苏", "老杨", "老爷爷", "小妹妹", "老奶奶", "大鹏", "大明", "大鹏展翅", "你好", "hello",
"hi", "x", "xiao"
];
$('#txt').on('compositionstart', function() {
flag = false;
})
$('#txt').on('compositionend', function() {
flag = true;
})
$('#txt').on('input', function() {
var _this = this;
setTimeout(function() {
if (flag) {
autoSearch($(_this).val(), "result-list", test_list)
}
}, 0)
});
function autoSearch(val, sel, tlist) {
$("#" + sel).html(""); //清空列表
var larr = new Array();
var n = 0;
if (val != "") {
tlist.forEach(function(va) {
if (va.includes(val)) {
larr[n++] = va;
}
});
if (larr.length != 0) {
var listr = "";
larr.forEach(function(value) {
listr += '<li>' + value + '</li>';
});
$("#" + sel).removeClass("hide").html(listr);
} else {
$("#" + sel).addClass("hide")
}
} else {
$("#" + sel).addClass("hide")
}
}
$(document).on("click", function(e) {
var e = e ? e : window.event;
var tar = e.srcElement || e.target;
//if (tar.id != "result-list") {
if (!$("#result-list").hasClass("hide")) {
while (tar) {
if (tar.id && tar.id == "result-list") {
return;
}
tar = tar.parentNode;
}
$("#result-list").addClass("hide");
}
//}
})
</script>
</body>
</html>