核心就是 记住上一次浏览的位置,记住滚动条所处的位置
// 当页面刷新之后 重新回到上次滚动条 所处的位置
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)
}