HTML页面
<style>
/* 固定定位的搜索框容器 */
.fixed-top-search {
position: fixed; /* 固定定位,悬浮不随滚动移动 */
top: 0; /* 锁定到页面顶部 */
right: 20px; /* 水平靠右 20px,可改 left: 20px 靠左,或 left: 50%; transform: translateX(-50%) 居中 */
z-index: 9999; /* 最高层级,避免被遮挡 */
padding: 10px 0; /* 上下内边距,让搜索框更美观 */
width: 320px; /* 搜索框宽度,可调整 */
}
</style>
<!-- 悬浮搜索框 -->
<div class="fixed-top-search">
<div class="input-group">
<input type="text" class="form-control search" placeholder="请输入搜索内容" aria-label="搜索">
<span class="input-group-addon">
输入名称
</span>
</div>
</div>
JS处理
function clearHighlight() {
// 找到所有高亮的span,直接替换为文本内容,避免unwrap的转义问题
$('span.bg-danger').each(function() {
var $this = $(this);
// console.log($this.text());
// 替换span为其文本内容(纯文本,无HTML解析)
// $this.replaceWith($this.text());
$this.parent().text($this.parent().text())
});
}
// 搜索字符串并添加 bg-danger 类
function searchAndHighlight(keyword) {
if (!keyword.trim()) return;
// 遍历所有文本节点(排除 script、style 标签)
$('body :not(script, style)').contents().each(function() {
// 只处理文本节点
if (this.nodeType === Node.TEXT_NODE) {
var text = $(this).text();
// text=text.replace(/"/g,"");
const regex = new RegExp(`(${keyword})`, 'gi');
// 匹配到关键词时,用 span 包裹
if (regex.test(text)) {
const newHtml = text.replace(regex, '<span class="bg-danger">$1</span>');
$(this).replaceWith(newHtml);
// $(this).addClass('bg-danger')
}
}
});
}
$(".search").on("input", function(){
var se = $(this).val().trim(); // 去除首尾空格,避免无效查询
if (se) {
clearHighlight();
searchAndHighlight(se); // 有内容则高亮
}
});