当前位置:首页 > JavaScript

js实现电子书页面搜索

2026-01-31 12:10:31JavaScript

实现电子书页面搜索的步骤

准备工作
确保电子书内容已加载到网页中,可以是纯文本、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' });
}

注意事项

js实现电子书页面搜索

  • 对特殊字符进行转义,避免正则表达式错误
  • 考虑添加搜索选项(如区分大小写、全字匹配)
  • 对于动态加载的电子书,确保内容完全加载后再执行搜索

标签: 电子书页面
分享给朋友:

相关文章

vue如何实现默认页面

vue如何实现默认页面

Vue 实现默认页面的方法 在 Vue 项目中,通常需要设置一个默认页面(如首页或登录页)作为用户访问时的初始页面。可以通过路由配置实现。 配置路由默认跳转 在 Vue Router 中,使用 re…

php实现页面跳转

php实现页面跳转

PHP 页面跳转方法 在 PHP 中,可以通过多种方式实现页面跳转,以下是几种常见的方法: 使用 header() 函数 header() 函数是 PHP 中最常用的跳转方法,通过发送 HTTP 头…

如何react页面

如何react页面

创建 React 页面 使用 create-react-app 快速初始化项目: npx create-react-app my-app cd my-app npm start 基础页面结构 在 s…

vue实现页面

vue实现页面

Vue 实现页面的基本方法 安装 Vue.js 依赖 通过 npm 或 yarn 安装 Vue.js: npm install vue # 或 yarn add vue 创建 Vue 实例 在…

js 实现页面刷新

js 实现页面刷新

使用 location.reload() location.reload() 是原生 JavaScript 提供的页面刷新方法。调用该方法会重新加载当前页面,相当于点击浏览器的刷新按钮。 // 基本…

jquery加载页面

jquery加载页面

jQuery 加载页面内容的方法 使用 .load() 方法 通过 AJAX 请求加载远程数据并插入到指定元素中。适用于加载部分页面片段。 $("#targetElement").load("ext…