返回
全局搜索功能在JS中的实现
前端
2023-10-16 23:22:49
在JS中,我们可以模拟浏览器的全局搜索功能,通过搜索指定模块的对应值并添加高亮显示等效果,从而实现搜索高亮功能。
实现步骤:
1. 创建搜索框和按钮
<input type="text" id="search-input">
<button id="search-button">搜索</button>
2. 定义一个函数来处理搜索
function search() {
const input = document.getElementById("search-input");
const searchValue = input.value;
// 在此添加搜索逻辑...
}
3. 监听搜索按钮的点击事件
document.getElementById("search-button").addEventListener("click", search);
4. 编写搜索逻辑
在搜索函数中,我们可以使用正则表达式来匹配指定模块的对应值。例如,以下代码搜索一个名为"模块1"的模块中的"值1":
const regex = new RegExp("模块1: 值1", "gi");
5. 添加高亮显示
找到匹配项后,我们可以使用DOM操作将它们添加高亮显示。例如,以下代码将所有匹配项添加背景颜色:
const matches = document.querySelectorAll("p");
matches.forEach((match) => {
match.style.backgroundColor = "#FFFF00";
});
完整的代码示例:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="text" id="search-input">
<button id="search-button">搜索</button>
<p>模块1: 值1</p>
<p>模块2: 值2</p>
<p>模块3: 值3</p>
<script>
function search() {
const input = document.getElementById("search-input");
const searchValue = input.value;
const regex = new RegExp(searchValue, "gi");
const matches = document.querySelectorAll("p");
matches.forEach((match) => {
if (match.textContent.match(regex)) {
match.style.backgroundColor = "#FFFF00";
}
});
}
document.getElementById("search-button").addEventListener("click", search);
</script>
</body>
</html>
使用注意事项:
- 确保搜索值与指定模块的对应值相匹配。
- 正则表达式可以根据实际需求进行调整。
- 高亮显示效果可以根据实际情况自定义。