在数字出版领域,EPUB 是一种广泛使用的电子书格式,支持多种设备和平台。为了方便地在网页中嵌入 EPUB 电子书阅读功能,我们可以使用开源库 epub.js 来快速构建一个功能齐全的阅读器。本文将介绍如何使用 HTML、CSS 和 JavaScript 搭建一个基础的 EPUB 阅读器。
效果演示
项目概述
本项目主要包含以下主要功能:
- 加载并展示 EPUB 文件
- 支持上一页 / 下一页翻页操作
- 显示书籍目录(TOC)
- 记录阅读进度
准备工作
准备一本 EPUB 格式的电子书文件,并将其放置在项目根目录下供加载使用。
引入必要的依赖文件,其中 jszip 是处理 EPUB 文件(本质上是 ZIP 压缩包)所必需的,epub.js 是主库文件,提供了完整的 EPUB 解析与渲染能力。
epub.js下载地址:https://github.com/futurepress/epub.js
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.5/jszip.min.js"></script>
<script src="./epub.js"></script>
页面结构与样式设计
创建 HTML 结构
<div class="controls">
<button onclick="toggleTOC()">目录</button>
<button onclick="prevPage()">上一页</button>
<button onclick="nextPage()">下一页</button>
</div>
<div id="toc-panel"></div>
<div id="viewer"></div>
<div class="progress" id="progress"></div>
设计 CSS 样式
body {
margin: 0;
padding: 20px;
font-family: Arial, sans-serif;
background-color: #f5f5f5;
transition: background-color 0.3s;
}
#viewer {
width: 90%;
height: 80vh;
margin: 20px auto;
box-shadow: 0 0 10px rgba(0,0,0,0.2);
background: white;
}
.controls {
display: flex;
gap: 10px;
justify-content: center;
margin: 20px 0;
}
button {
padding: 8px 16px;
cursor: pointer;
background: #007bff;
color: white;
border: none;
border-radius: 4px;
transition: background 0.3s;
}
button:hover {
background: #0056b3;
}
.progress {
text-align: center;
color: #666;
}
#toc-panel {
position: fixed;
left: -300px;
top: 0;
width: 280px;