效果如下:
完整代码:
<!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">
<style>
header {
width: 500px;
height: 30px;
margin: 50px auto;
}
input {
width: 430px;
height: 30px;
}
.show {
display: none;
padding-left: 10px;
width: 420px;
border: 1px solid #ccc;
}
</style>
<title>Document</title>
</head>
<body>
<header>
<input type="search" placeholder="请输入课程">
<button>提交</button>
<div class="show"></div>
</header>
<script>
let arr = ['web前端精英特训班 980元', 'HTML核心技术 199元', 'Vue核心技术 599元', 'CSS核心技术 299元',
'JavaScript核心技术 399元'
];
var header = document.querySelector('header');
var show = header.querySelector('.show');
var input = header.querySelector('input');
var newStr = '';
input.addEventListener('keyup', function () {
show.style.display = 'block';
let str = this.value;
let flag;
let num = 0;
show.innerHTML = '';
for (let i = 0; i < arr.length; i++) {
flag = arr[i].indexOf(str)
if (flag == -1) {
num++;
} else {
num--;
show.innerHTML += '<p>' + arr[i] + '</p>';
}
}
if (num == arr.length || str == '') {
show.innerHTML = '<p>暂无搜索结果</p>'
}
})
input.addEventListener('blur', function () {
show.style.display = 'none';
})
</script>
</body>
</html>