<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>document</title>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<style>
#val {
width: 200px;
height: 20px;
border-radius: 8px 0px 0px 8px;
border: 1px solid #999;
}
#ok {
width: 40px;
height: 25px;
position: relative;
left: -5px;
background-color: #4e6ef2;
color: #fff;
border-radius: 0px 8px 8px 0px;
border: 1px solid #999;
}
.content {
width: 600px;
height: 500px;
margin: 0 auto;
}
.show {
display: none;
width: 200px;
height: 150px;
border: solid 1px black;
}
.possible_input {
padding: 5px;
cursor: pointer;
}
.possible_input:hover {
color: #4e6ef2;
}
</style>
</head>
<body>
<div class="content">
<div class="serach">
<input type="text" id="val" placeholder="请输入内容" autocomplete="on">
<button id="ok">ok</button>
</div>
<div class="show" id="show"></div>
</div>
<script>
// 点击页面中的其他位置时,让show盒子消失
$(document).click(function () {
$("#show").css("display","none");
});
//以数组为例,可以连接数据库,进行查询数据
let arr = ['百度111', '谷歌111', 'react111', 'javascript111', 'anglar1111', 'html66', 'jquery2222','微软222222', 'python,2222',
'flask222', 'django222', 'java222','vue666', 'css66666', 'c语言666', 'c++666'];
//先完成,展示区域的显示与隐藏
let input = document.getElementById("val");
let show = document.getElementById("show");
input.onkeyup = function () {
//当键盘抬起时触发
show.style.display = 'block';
//input.value和arr的每一项进行匹配 用indexof():方法可返回某个指定的字符串值在字符串中首次出现的位置, 匹配到返回下标,匹配不到返回-1
let str = '';
arr.forEach((item) => {//forEach()中第一个元素item,代表数组中的元素,每一项
let res = item.indexOf(input.value);
if (res != -1) {
var count=(str.match(/possible_input/g)||[]).length;
if(count>=5){//最多只显示5条可能输入的内容
return;
}
str += `<div class="possible_input" onclick=change_input_val(this)>${item}</div>`;
};
});
console.log(str);
//判断input.value为空或者str数组中没有,给用户一个提示
if (!input.value || !str) {
show.innerHTML = '<div>暂无结果</div>';
} else {
show.innerHTML = str;
};
};
function change_input_val(elem){
$("#val").val($(elem).text())
show.style.display = 'block';
}
</script>
</body>
</html>