js实现电子书页面搜索
实现电子书页面搜索的步骤
准备工作
确保电子书内容已加载到网页中,可以是纯文本、HTML格式或通过API获取的数据。搜索功能通常需要遍历文本内容并高亮显示匹配项。
HTML结构示例
创建一个搜索框和结果显示区域:
<input type="text" id="searchInput" placeholder="输入搜索内容">
<button id="searchButton">搜索</button>
<div id="ebookContent">这里是电子书文本内容...</div>
JavaScript实现搜索逻辑
监听搜索按钮点击事件,获取输入内容并执行搜索:
document.getElementById('searchButton').addEventListener('click', function() {
const searchTerm = document.getElementById('searchInput').value.trim();
if (searchTerm) {
searchEbookContent(searchTerm);
}
});
function searchEbookContent(searchTerm) {
const ebookContent = document.getElementById('ebookContent');
const content = ebookContent.textContent || ebookContent.innerText;
const regex = new RegExp(searchTerm, 'gi');
const highlightedContent = content.replace(regex, match => `<span class="highlight">${match}</span>`);
ebookContent.innerHTML = highlightedContent;
}
高亮样式
添加CSS样式以突出显示搜索结果:
.highlight {
background-color: yellow;
font-weight: bold;
}
优化搜索性能
对于大型电子书,考虑分页或懒加载内容,避免一次性处理过多文本:
function searchInChunks(content, searchTerm) {
const chunkSize = 10000; // 分块大小
let result = '';
for (let i = 0; i < content.length; i += chunkSize) {
const chunk = content.substring(i, i + chunkSize);
result += chunk.replace(new RegExp(searchTerm, 'gi'), match => `<span class="highlight">${match}</span>`);
}
return result;
}
添加搜索导航
实现上一个/下一个匹配项导航功能:
let currentMatchIndex = 0;
let matches = [];
function navigateSearch(direction) {
if (matches.length === 0) return;
currentMatchIndex = (currentMatchIndex + direction + matches.length) % matches.length;
matches[currentMatchIndex].scrollIntoView({ behavior: 'smooth', block: 'center' });
}
注意事项
- 对特殊字符进行转义,避免正则表达式错误
- 考虑添加搜索选项(如区分大小写、全字匹配)
- 对于动态加载的电子书,确保内容完全加载后再执行搜索







