Butterfly主题魔改:阅读进度条

473 字
2 分钟
Butterfly主题魔改:阅读进度条

前言#

虽然说Butterfly本身就有阅读进度功能,但是还是想魔改一下,在页面顶端加一个阅读进度条。 不需要修改主题文件,只需要外部注入js和css即可实现,代码由deepseek生成,自己修改了部分内容 (增加了一些bug)。 适配pjax,能动态检测页面高度变化并进行进度条更新。

JS#

class ReadingProgress {
constructor() {
this.progressBar = null
this.observer = null
this.lastHeight = 0
this.init()
this.bindPjaxEvents()
}
// 初始化进度条
init() {
// 创建或复用进度条元素
this.progressBar = document.querySelector('.read-progress') ||
Object.assign(document.createElement('div'), {className: 'read-progress'})
if (!document.contains(this.progressBar)) {
document.body.appendChild(this.progressBar)
}
// 动态计算参数
this.calculatePageHeight()
this.bindScrollEvent()
this.bindResizeObserver()
}
// 计算页面实际高度并更新进度条
calculatePageHeight() {
//检测页面高度是否变化
if (this.lastHeight != document.body.scrollHeight){
this.pageHeight = document.body.scrollHeight
this.lastHeight = this.pageHeight
let progress = (document.documentElement.scrollTop / (this.pageHeight - window.innerHeight)) * 100
this.progressBar.style.width = Math.min(progress, 100).toFixed(1) + '%'
}
}
// 滚动事件处理
bindScrollEvent() {
let isScrolling;
const updateProgress = () => {
// 滚动高度 / (页面高度 - 视口高度) * 100
let progress = (document.documentElement.scrollTop / (this.pageHeight - window.innerHeight)) * 100
this.progressBar.style.width = Math.min(progress, 100).toFixed(1) + '%'
isScrolling = false
};
window.addEventListener('scroll', () => {
if (!isScrolling) {
window.requestAnimationFrame(()=>{
setTimeout(updateProgress,50) //节流
})
isScrolling = true
}
});
}
// 监听DOM变化
bindResizeObserver() {
this.observer = new MutationObserver(() => {
this.calculatePageHeight()
});
this.observer.observe(document.querySelector(".layout"), { //这里设置成某个页面元素或者整个页面
childList: true,
subtree: true,
attributes: true
});
}
// 销毁旧监听(Pjax切换时)
destroy() {
window.removeEventListener('scroll', this.handleScroll)
if (this.observer) this.observer.disconnect()
}
// Pjax事件绑定
bindPjaxEvents() {
document.addEventListener('pjax:send', () => this.destroy())
document.addEventListener('pjax:complete', () => this.init())
}
}
// 初始化阅读进度条
document.addEventListener('DOMContentLoaded', () => {
new ReadingProgress()
});

CSS#

.read-progress {
  position: fixed;
  top: 0;
  left: 0;
  height: 2px;
  z-index: 100;
  width: 0%;
  background: #26ff84b6;
  transition: width .1s;
  transform-origin: left;
}

隐藏滚动条#

在PC端的滚动条会占用一部分位置,导致进度条不能完全覆盖。解决方法是使用css隐藏滚动条。

::-webkit-scrollbar {
  display: none;
}
html{
  scrollbar-width: none;
  -ms-overflow-style: none;
}

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

Butterfly主题魔改:阅读进度条
https://blog.dotuoodo.top/posts/reading-progress/
作者
DOTUOODO
发布于
2025-02-28
许可协议
CC BY-NC-SA 4.0

评论

Profile Image of the Author
DOTUOODO
Nothing is immortal, but at least we can be extraordinary.
公告
欢迎来到我的博客!目前还在施工中...
分类
标签

文章目录