html部分
css部分:
* {
padding: 0;
margin: 0;
}
.icon {
width: 20em;
height: 20em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
.box {
width: 600px;
margin: 50px auto;
}
.box-img {
margin: auto;
text-align: center;
}
.box-input {
width: 100%;
height: 40px;
/* display: inline-block; */
line-height: 40px;
position: relative;
vertical-align: middle;
}
.import {
/* border: none; */
width: 80%;
height: 100%;
border: 1px rgb(66, 66, 66) solid;
box-sizing: border-box;
padding: 0 40px 0 10px;
margin: 0;
position: relative;
/* top: -2px; */
}
.box-in {
width: 100%;
height: 32px;
text-align: center;
line-height: 32px;
}
.sub {
height: 100%;
width: 18%;
background: #3385ff;
border: none;
color: white;
font-size: 20px;
box-sizing: border-box;
/* margin-left: 10px; */
position: absolute;
top: 1px;
}
.show-ul li {
list-style-type: none;
padding-left: 10px;
}
.show-ul {
width: 80%;
border: 1px rgb(86, 87, 86) solid;
border-top: none;
display: none;
}
.showb {
color: red;
}
JS部分;
选模拟一串数据,获取DOM节点
var data = ["人工智能", "智能填写", "前端", "数据1", "JS智能填写智能显示", "人工智能2", "智能表单", "JS事件处理"];
var inputText = document.getElementsByClassName("import")[0];
var showUl = document.getElementsByClassName("show-ul")[0];
设置键盘输入监听
inputText.addEventListener("keyup", function () {
_this = this;
//获取input输入值
var textValue = _this.value;
//存储输出数组
var getData = [];
}
监听执行主方法
function matching(currentValue) {
if (currentValue.indexOf(textValue) > -1) {
//调用关键字添加样式方法
var dataStyle = addDataStyle(currentValue, textValue);
//装入输出数组
getData.push(dataStyle);
}
}
if (textValue) {
//遍历模拟的数组
data.filter(matching);
} else {
//调用删除ul方法
cancelUl();
}
if (getData.length > 0) {
//调用添加li方法
addDomeLi(getData);
}
添加LI标签方法
//添加li
function addDomeLi(data) {
var showLiHtml = "";
for (let i = 0; i < data.length; i++) {
showLiHtml += "" + data[i] + " ";
}
showUl.innerHTML = showLiHtml;
showUl.style.display = "block";
}
无输入时隐藏UL标签
function cancelUl() {
showUl.innerHTML = "";
showUl.style.display = "none"
}
给输入的关键字添加标记变色
function addDataStyle(inData, textValue) {
//关键字数组
var matchingData = [];
//输出数组
var outData = []
//装入
matchingData.push(inData);
//遍历 加样式
matchingData.map(
function (currentValue) {
//拆分输入字符串为数组
var tmpArray=currentValue.split(textValue);
console.log(tmpArray);
//装入拆分的数组
currentValue=tmpArray.join('' + textValue + "");
console.log(currentValue);
// currentValue = currentValue.replace(textValue, '' + textValue + "");
//装入
outData.push(currentValue);
}
);
return outData;
}
总结:先获取input的值和模拟数据data进行对比 if (currentValue.indexOf(textValue) > -1)
再将获取的值拆分为数组 currentValue.split(textValue)
将拆分的数组添加样式标签后装入tmpArray.join('' + textValue + "")即可;
调用添加LI标签方法,输出显示该数组