核心就是 记住上一次浏览的位置,记住滚动条所处的位置
// 当页面刷新之后 重新回到上次滚动条 所处的位置
window.scrollTop(0, 0);
// 滚动到 上次访问位置
const scrollToView = () => {
let scrollHeight = localStorage.getItem('scrollHeight');
if(scrollHeight) {
setTimeout(() => {
window.scrollTo({
top: scrollHeight,
behavior: "smooth"
});
}, 300)
}
}
// 监听用户滚动位置
const listenScrollTop = () => {
const debounce = () => {
let timer = null;
return () => {
if(timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
localStorage.setItem('scrollHeight', window.pageYOffset ||
document.body.scrollTop || document.documentElement.scrollTop)
}, 500)
}
}
this.scrollFn = debounce();
window.addEventListener('scroll', this.scrollFn)
}
网页滚动位置记忆
本文介绍了一种使用JavaScript和localStorage来记录并恢复网页滚动位置的方法。通过监听页面滚动事件,并在页面加载时平滑滚动到之前的位置,实现了良好的用户体验。
4201

被折叠的 条评论
为什么被折叠?



