js实现电子书页面搜索
实现电子书页面搜索的 JavaScript 方法
核心思路
通过遍历电子书文本内容,匹配用户输入的关键词,并高亮显示匹配结果。需处理分页、动态加载等场景。
基础文本搜索实现
function searchInText(content, keyword) {
const regex = new RegExp(keyword, 'gi');
return content.replace(regex, match => `<span class="highlight">${match}</span>`);
}
调用示例:
document.getElementById('book-content').innerHTML =
searchInText(bookContent, userInput);
分页电子书搜索方案
数据结构准备
假设电子书分页数据存储在数组中:
const bookPages = [
{ id: 1, content: "第一章内容..." },
{ id: 2, content: "第二章内容..." }
];
跨页搜索函数
function searchAcrossPages(keyword) {
const results = [];
bookPages.forEach(page => {
if (page.content.includes(keyword)) {
const highlighted = searchInText(page.content, keyword);
results.push({
pageId: page.id,
highlightedContent: highlighted
});
}
});
return results;
}
动态加载优化
对于大型电子书,采用懒加载策略:
async function searchInLargeBook(keyword) {
let currentPage = 1;
const results = [];
while (true) {
const pageContent = await fetchPageContent(currentPage);
if (!pageContent) break;
if (pageContent.includes(keyword)) {
results.push({
page: currentPage,
content: searchInText(pageContent, keyword)
});
}
currentPage++;
}
return results;
}
高亮样式建议
CSS 样式示例:
.highlight {
background-color: yellow;
color: black;
font-weight: bold;
}
性能优化技巧
- 使用 Web Workers 处理大型文本搜索
- 实现搜索索引预处理:
const searchIndex = {}; bookPages.forEach(page => { const words = page.content.split(/\s+/); words.forEach(word => { if (!searchIndex[word]) searchIndex[word] = []; searchIndex[word].push(page.id); }); });
高级功能扩展
实现模糊搜索:
function fuzzySearch(text, keyword) {
const pattern = keyword.split('').join('.*?');
const regex = new RegExp(pattern, 'i');
return regex.test(text);
}
注意事项
- 处理大小写敏感需求
- 考虑正则表达式特殊字符转义
- 移动端触摸事件支持
- 搜索结果分页显示







