B2主题文章阅读进度条与目录导航二开实现

功能说明

阅读进度条与文章目录能够显著提升长文阅读体验。本文给出在 B2 子主题中通过前端脚本实现这两个能力的完整方案。

一、阅读进度条

在 single 页面注入一段轻量 JS,监听滚动位置更新顶部进度条:

Text
window.addEventListener('scroll', function () {
    var h = document.documentElement;
    var pct = h.scrollTop / (h.scrollHeight - h.clientHeight) * 100;
    var bar = document.getElementById('ji-read-bar');
    if (bar) bar.style.width = pct + '%';
});
Text
#ji-read-bar {
    position: fixed; top: 0; left: 0; height: 3px; z-index: 999;
    background: var(--primary-color, #1565c0);
    width: 0; transition: width .1s linear;
}

二、文章目录生成

遍历文章内 h2/h3 自动生成锚点目录,并支持点击平滑滚动:

Text
function ji_build_toc() {
    var heads = document.querySelectorAll('.entry-content h2, .entry-content h3');
    var toc = document.getElementById('ji-toc');
    if (!heads.length || !toc) return;
    var html = '
    '; heads.forEach(function (h, i) { h.id = 'sec-' + i; html += '
  • ' + h.textContent + '
  • '; }); toc.innerHTML = html + '
'; } ji_build_toc();

三、目录吸顶与高亮

通过 IntersectionObserver 高亮当前章节,配合 position: sticky 实现目录跟随:

Text
.ji-toc-wrap { position: sticky; top: 80px; max-height: 70vh; overflow-y: auto; }

注意事项

  • 目录生成需在 DOM 渲染完成后执行,建议放在 window load 事件中。
  • 移动端目录建议折叠,避免遮挡正文。

给TA打赏
共{{data.count}}人
人已打赏
0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
签到成功