
本文详细介绍了如何使用javascript、html和css实现一个动态搜索功能。通过监听搜索框输入事件,实时过滤html列表(`
- `)中的数据,并高亮显示所有匹配的关键词。该教程涵盖了前端交互逻辑、样式设计和dom操作,旨在帮助开发者构建用户友好的搜索体验。
动态搜索与高亮显示列表项教程
在现代Web应用中,为用户提供高效的数据检索和展示功能至关重要。本文将指导您如何创建一个交互式搜索框,该搜索框能够实时过滤HTML列表中的内容,并高亮显示所有匹配的关键词,从而显著提升用户体验。
1. HTML结构:基础骨架
首先,我们需要构建页面的基本HTML结构,包括一个搜索输入框和用于展示列表项的无序列表。
全球顶尖大学列表
- Massachusetts Institute of Technology (MIT)
- Stanford University
- Harvard University
- California Institute of Technology (Caltech)
- University of Oxford
- University of Cambridge
- University of Chicago
- ETH Zurich - Swiss Federal Institute of Technology
- University of California, Berkeley (UCB)
- Aalborg University (Denmark)
- Aalto University (Finland)
- Aarhus University (Denmark)
- Abdullah Gül University (Turkey)
- Abertay University (United Kingdom)
- Aberystwyth University (United Kingdom)
- Abia State University (Nigeria)
- Abilene Christian University (United States)
- Adam Mickiewicz University (Poland)
- Addis Ababa University (Ethiopia)
- Adelphi University (United States)
- Princeton University
- input 元素:类型为 search,具有 id="search-box" 和 class="search_box",用于用户输入搜索关键词。
- ul 元素:具有 id="world-universities_list" 和 class="world-universities_list",包含所有待搜索的列表项。
- li 元素:每个列表项都带有 class="university"。
2. CSS样式:美化与高亮
为了使界面更具吸引力,并定义高亮显示的效果,我们需要添加一些CSS样式。其中,.highlight 类是实现高亮的关键。
body {
margin: 0;
padding: 0;
font-family: 'Poppins', sans-serif;
}
*, *::before, ::after {
padding: 0;
margin: 0;
box-sizing: border-box;
}
ul {
list-style-type: none;
padding: 0;
margin: 0;
}
main {
background-color: rgb(255, 255, 255);
margin: 1.5rem;
display: flex;
flex-direction: column;
}
.title {
text-align: center;
color: rgb(221, 4, 58);
font-weight: 600;
font-family: 'Poppins', sans-serif;
font-size: 2rem;
margin-top: 2rem;
}
.search_box {
display: block;
width: 100%;
height: 2rem;
border-radius: 0.5rem;
border: 1.5px solid #0000002c;
margin-top: 2rem;
outline: none;
padding: 2px;
}
.world-universities_list {
background-color: rgb(104, 7, 39);
color: white;
padding: 1.5rem;
border-radius: 1rem;
margin-top: 3rem;
}
.university:not(.last-u) {
margin-bottom: 2rem;
}
/* 高亮样式 */
.highlight {
background-color: aqua; /* 高亮背景色 */
font-weight: bold; /* 高亮字体加粗 */
color: black; /* 确保高亮文字清晰可见 */
padding: 2px 0; /* 适当内边距 */
border-radius: 3px; /* 轻微圆角 */
}3. JavaScript逻辑:核心交互
JavaScript代码负责监听用户的输入,并根据输入内容实时更新列表的显示和高亮。
立即学习“Java免费学习笔记(深入)”;
// 获取DOM元素
const searchBox = document.getElementById("search-box");
const universities = document.querySelectorAll(".university"); // 获取所有大学列表项
// 定义搜索功能函数
const searchUniversity = () => {
// 监听搜索框的键盘抬起事件
searchBox.addEventListener("keyup", () => {
// 获取搜索框当前值,转换为小写并去除所有空格
const searchBoxInput = searchBox.value.toLowerCase();
const noWhiteSpaceInput = searchBoxInput.replace(/\s/g, ""); // 移除所有空格
// 遍历所有大学列表项
universities.forEach((university) => {
// 获取列表项的原始文本内容,转换为小写并去除所有空格
const universityName = university.textContent.toLowerCase().replace(/\s/g, "");
// 存储原始文本内容,用于后续高亮操作
const originalText = university.textContent;
// 1. 过滤逻辑:根据搜索框输入显示或隐藏列表项
if (universityName.includes(noWhiteSpaceInput)) {
university.style.display = "block"; // 匹配则显示
} else {
university.style.display = "none"; // 不匹配则隐藏
}
// 2. 高亮逻辑:如果搜索框有输入,则高亮匹配部分
if (noWhiteSpaceInput.length > 0) {
// 创建正则表达式,'gi' 表示全局匹配和不区分大小写
const regex = new RegExp(`(${noWhiteSpaceInput})`, "gi");
// 使用replace方法,将匹配到的内容用标签包裹,并应用highlight样式
// $1 代表正则表达式中第一个捕获组(即括号内的内容)
const highlightedText = originalText.replace(regex, "$1");
university.innerHTML = highlightedText; // 更新列表项的HTML内容
} else {
// 如果搜索框为空,则恢复列表项的原始文本,移除所有高亮
university.innerHTML = originalText;
}
});
});
};
// 调用搜索功能函数,启动监听
searchUniversity();代码详解:
-
DOM元素获取:
- searchBox:通过 id 获取搜索输入框元素。
- universities:通过 class 获取所有
- 列表项元素,返回一个 NodeList。
-
事件监听:
- searchBox.addEventListener("keyup", ...):当用户在搜索框中输入并抬起键盘时,会触发回调函数。
-
输入处理:
- searchBoxInput = searchBox.value.toLowerCase():获取搜索框的当前值,并转换为小写,实现不区分大小写的搜索。
- noWhiteSpaceInput = searchBoxInput.replace(/\s/g, ""):移除输入中的所有空格,使得搜索“MassachusettsInstitute”也能匹配“Massachusetts Institute”。
-
列表项遍历:
- universities.forEach((university) => { ... }):遍历所有大学列表项。
- universityName = university.textContent.toLowerCase().replace(/\s/g, ""):对每个列表项的文本内容进行与搜索输入相同的标准化处理。
- originalText = university.textContent:存储原始文本,以便在清空搜索框时恢复。
-
过滤逻辑:
- if (universityName.includes(noWhiteSpaceInput)):使用 includes() 方法判断列表项文本是否包含搜索输入。
- university.style.display = "block" 或 "none":根据匹配结果显示或隐藏列表项。
-
高亮逻辑:
- if (noWhiteSpaceInput.length > 0):只有当搜索框有内容时才执行高亮。
- const regex = new RegExp((${noWhiteSpaceInput}), "gi");:创建一个正则表达式。
- noWhiteSpaceInput 是搜索关键词。
- () 创建一个捕获组,以便在替换时引用匹配到的文本。
- g (global):查找所有匹配项,而不是找到第一个就停止。
- i (case-insensitive):不区分大小写匹配。
- const highlightedText = originalText.replace(regex, "$1");:使用 replace() 方法替换匹配到的文本。
- $1 引用了正则表达式中第一个捕获组的内容,即实际匹配到的关键词。
- 将匹配到的关键词包裹在 标签中。
- university.innerHTML = highlightedText;:将包含高亮标签的新HTML内容赋值给列表项的 innerHTML。
- else { university.innerHTML = originalText; }:如果搜索框为空,则将列表项的 innerHTML 恢复为原始文本,移除所有高亮。
4. 注意事项与总结
- 性能考虑:对于包含成千上万个列表项的超大型列表,每次 keyup 事件都遍历并修改DOM可能会导致性能问题。在这种情况下,可以考虑使用虚拟列表(Virtual List)或进行节流/防抖(Throttling/Debouncing)优化。
- 安全性:直接使用 innerHTML 插入用户输入内容时,存在XSS(跨站脚本攻击)风险。但在本例中,我们只将原始列表项文本和用户输入(用于高亮)结合,风险较低。如果列表项内容或搜索关键词可能包含恶意脚本,则需要对输入进行严格的净化处理。
-
用户体验:
- 提供清晰的占位符(placeholder)提示用户搜索功能。
- 确保高亮颜色与背景色有足够的对比度,以保证可读性。
- 在搜索结果为空时,可以显示一条“未找到匹配项”的消息,而不是仅仅隐藏所有列表项。
通过上述步骤,您已经成功实现了一个功能完善且用户友好的实时搜索和高亮显示功能。这个模式在许多Web应用中都非常常见,掌握它将对您的前端开发技能大有裨益。










