仿百度联想词
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>仿百度联想词</title>
</head>
<body>
<div class="autoComplete">
<h2>仿百度联想词技术</h2>
<div><input type="text" id='autoComplete'/></div>
<div id="autoCompleteList"></div>
</div>
</body>
</html>
css部分
<style>
.autoComplete {
background-color: #f6f6f6;
width: 100%;
height: 200px;
}
#autoComplete {
width: 500px;
border: 0px;
height: 35px;
border: 1px solid #ccc;
}
#autoCompleteList {
display: none;
margin-top: 0px;
width: 500px;
border: 1px solid #ccc;
}
#autoCompleteList div{
width: 500px;
height: 35px;
line-height: 33px;
cursor: pointer;
}
</style>
js代码
<script>
window.onload = function (){
let lxWordStore = [//联想词库
"美女","长发美女","外国美女","火影忍者","海贼王",
"JavaScript编程","JavaScript教程","JavaScript深入浅出",
"HTML5","HTML入门"
],
thread = -1; //超时填充线程
function createAutoHtml(autoCompleteList,str){
let _html="",
i,
_lxWordStore=lxWordStore,
regStr=null,
n=0,
v="";
regStr=new RegExp("^("+str+")","g");//匹配合适的联想词
for(i in _lxWordStore){//检索匹配词
if(n>=3){
break;//限制最多3个
}
v=_lxWordStore[i];
if (regStr.test(v)){
n++;
_html+="<div οnclick='addContent(this)'>"+v+"</div>";
}
}
if (!_html){//如果不存在联想词,隐藏联想框
autoCompleteList.style.display="none";
return false;
}else{
autoCompleteList.innerHTML = _html;
autoCompleteList.style.display="block";
return true;
}
}
function getTypeElement(es,type){//获取指定类型的节点
let esLen = es.length,
i=0,
eArr = [],
esl=null;
for (;i<esLen;i++){
esl=es[i];
if (esl.nodeName.replace("#","").toLocaleLowerCase()==type){
eArr.push(esl);
}
}
return eArr;
}
function autoComplete(){
console.log(lxWordStore)
let autoComplete=document.getElementById('autoComplete'),
autoCompleteList=null,
str="";
let createAuto=function (_this){
clearTimeout(thread);//清除定时
str=_this.value;
str=str.replace("[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]");
if (!str){
return;
}
thread=setTimeout(function (){
if (str.length>2&&!lxWordStore[str]){
lxWordStore[str]=str;//填充词库
}
},500)
autoCompleteList=document.getElementById('autoCompleteList');
//构建联想词,不存在联想词则不执行事件绑定
if (!createAutoHtml(autoCompleteList,str)){
return;
}
//绑定事件
let autoCompleteLists=getTypeElement(autoCompleteList.childNodes,"div"),
i=0,
l=autoCompleteLists.length;
}
autoComplete.onkeyup=function (){
createAuto(this);
}
autoComplete.onfocus=function (){
createAuto(this);
}
}
autoComplete();
};
</script>
测试