Files
ClassContent/历届学生/陈一航/2020-04-02/search.html
2024-09-27 02:06:13 +08:00

85 lines
3.0 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>仿照百度搜索提示建议</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
.main {
width: 400px;
margin: 30px auto;
}
.none {
display: none;
}
</style>
</head>
<body>
<div class="main">
<input class="search_key" type="text" placeholder="输入关键字">
<ul class="search_list none">
</ul>
</div>
</body>
<script>
// 获取输入框input的html
var searchKey = document.querySelector(".search_key");
// 获取建议列表的父容器
var searchList = document.querySelector(".search_list");
// 搜索建议数组
// 今天天气不错
// <span>天气</span>
var KeyWord = ['今天天气不错','心情不错', '今天不上课','我要学习HTML', '学习JS不错', '天气是阴天'];
// 存放符合用户条件的数据
var NewKeyWord = [];
// 给input绑定输入事件
searchKey.oninput = function (e) {
// 判断用户输入输入内容,或者是否在删除内容
if (searchKey.value.length == 0 || e.data == null) {
// 清空上次搜索的数组
NewKeyWord = []
// 清空上次遗留的html
document.querySelector(".search_list").innerHTML = ""
// 把建议列表隐藏
searchList.className = "search_list none"
// 判断用户是否在删除,如果是 先清除上次的数组和html之后重新匹配运行
e.data == null ? PiPei() : ''
// 输入不为空,开始匹配
} else {
PiPei()
}
}
function PiPei() {
// 遍历搜索建议数组
KeyWord.forEach(function(val,index) {
// 只有在输入的长度不为0的情况下并且能够在 搜索建议数组 能匹配到数值的情况下才保存数据到新数组
if (searchKey.value.length != 0 && val.indexOf(searchKey.value) > -1) {
// 截取符合用户输入的关键词出来然后拼接成html带上颜色
var jqukey = `<span style="color: red">${val.substring(val.indexOf(searchKey.value), val.indexOf(searchKey.value) + searchKey.value.length)}</span>`
// 将拼接好带颜色的字符串 替换到 原本的字符串中,并覆盖原本字符串
val = val.replace(searchKey.value, jqukey)
// 保存到新数组
NewKeyWord.push(val)
}
});
// 遍历渲染到页面
NewKeyWord.forEach(function(val,index){
// 插入li标签到ul里面
document.querySelector(".search_list").innerHTML += `<li>${val}</li>`
});
// 显示 建议列表
searchList.className = "search_list"
}
</script>
</html>