You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular中基于epubJs实现电子书章节导航下拉选单

在Angular中实现epubJs章节下拉导航

1. 修改 reader.ts 逻辑

在组件类中定义章节列表变量,在EPUB加载完成后解析目录(TOC),并实现章节跳转方法:

import { Component, OnInit } from '@angular/core';
import * as Epub from 'epubjs';

@Component({
  selector: 'app-reader',
  templateUrl: './reader.component.html',
  styleUrls: ['./reader.component.css']
})
export class ReaderComponent implements OnInit {
  book: any;
  rendition: any;
  // 存储章节名称与对应跳转路径
  chapters: Array<{ label: string, href: string }> = [];

  ngOnInit(): void {
    this.initEpubReader();
  }

  initEpubReader(): void {
    // 初始化EPUB书籍,替换为你的电子书实际路径
    this.book = new Epub('assets/your-book.epub');
    this.rendition = this.book.renderTo('viewer', {
      width: '100%',
      height: '100%',
      flow: 'paginated'
    });

    // 书籍加载完成后解析目录结构
    this.book.loaded.then(() => {
      this.flattenToc(this.book.toc);
    });

    this.rendition.display();
  }

  // 递归处理树形TOC,转为一维列表
  private flattenToc(tocItems: any[]): void {
    tocItems.forEach(item => {
      // 仅添加可跳转的章节项
      if (item.href) {
        this.chapters.push({
          label: item.label,
          href: item.href
        });
      }
      // 递归处理子章节
      if (item.subitems?.length) {
        this.flattenToc(item.subitems);
      }
    });
  }

  // 章节跳转核心方法
  navigateToChapter(href: string): void {
    if (this.rendition && href) {
      this.rendition.display(href);
    }
  }
}

2. 修改 reader.html 下拉选单

在左上角的<select>元素中绑定章节列表与跳转事件:

<div class="reader-header">
  <!-- 章节下拉导航 -->
  <select (change)="navigateToChapter($event.target.value)">
    <option value="">请选择章节</option>
    <option *ngFor="let chapter of chapters" [value]="chapter.href">
      {{ chapter.label }}
    </option>
  </select>
</div>

<!-- EPUB渲染容器 -->
<div id="viewer"></div>

关键说明

  • 目录扁平化:epubJs返回的TOC是树形结构(包含嵌套子章节),通过递归函数flattenToc将其转为一维数组,适配下拉选单的展示需求。
  • 异步时机:必须在book.loaded回调中解析目录,确保书籍资源加载完成后才能获取到有效的TOC数据。
  • 跳转逻辑:直接调用epubJs原生API rendition.display(href) 实现章节跳转,保证兼容性。

内容的提问来源于stack exchange,提问作者Mohd Hassan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 11:36:58