来自 Knut Melvær 的一些巧妙技巧。
最终的技巧归结为找出您在页面上滚动了多少,并更改标题以显示它,例如
document.title = `${percent}% ${post.title}`
Knut 的技巧假设使用 React 并安装 一个额外的库。 我相信该库可以完成各种智能操作,但如果您想以“原生”风格执行此操作,我可能会使用类似这样的东西……
const percentLabel = document.querySelector("#percent");
const originalTitle = document.title;
window.addEventListener("scroll", () => {
let scrollTop = window.scrollY;
let docHeight = document.body.offsetHeight;
let winHeight = window.innerHeight;
let scrollPercent = scrollTop / (docHeight - winHeight);
let scrollPercentRounded = Math.round(scrollPercent * 100);
percentLabel.innerHTML = scrollPercentRounded;
document.title = `(${scrollPercentRounded}%) ${originalTitle}`;
});