前端页面中,如何让用户回到上次阅读的位置?

B站影视 日本电影 2025-09-19 12:10 1

摘要:// 记录滚动位置window.addEventListener('scroll', throttle(function {const scrollY = window.scrollY || document.documentElement.scrollTop

需要注意这些点:

// 记录滚动位置window.addEventListener('scroll', throttle(function {const scrollY = window.scrollY || document.documentElement.scrollTop; localStorage.setItem('lastScrollPosition', scrollY);}, 100)); // 节流函数降低性能消耗// 恢复位置window.addEventListener('DOMContentLoaded', => {const savedPosition = localStorage.getItem('lastScrollPosition');if (savedPosition) { window.scrollTo(0, parseInt(savedPosition)); }});// 节流函数实现function throttle(fn, delay) {let lastCall = 0;returnfunction(...args) { const now = Date.now; if (now - lastCall // 记录锚点元素IDdocument.querySelectorAll('.section').forEach(el => { el.addEventListener('click', => { const activeId = el.id; history.replaceState(null, '', `#${activeId}`); });});// 恢复滚动window.addEventListener('load', => {const hash = window.location.hash.slice(1);if (hash) { const target = document.getElementById(hash); target?.scrollIntoView({ behavior: 'smooth' }); }});// 记录最近可见的元素const observer = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting) { const elementId = entry.target.id; localStorage.setItem('lastVisibleElement', elementId); } });}, { threshold: 0.5 });// 观察所有章节元素document.querySelectorAll('.chapter').forEach(el => observer.observe(el));// 恢复时滚动到最近可见元素const lastElementId = localStorage.getItem('lastVisibleElement');if (lastElementId) {document.getElementById(lastElementId)?.scrollIntoView;}let lastKnownPos = 0;let ticking = false;window.addEventListener('scroll', => { lastKnownPos = window.scrollY;if (!ticking) { window.requestAnimationFrame( => { // 预测用户滚动方向 const viewportHeight = window.innerHeight; const predictPosition = lastKnownPos + (viewportHeight * 0.3); localStorage.setItem('predictPos', predictPosition); ticking = false; }); ticking = true; }});// 恢复时使用预测位置const savedPos = localStorage.getItem('predictPos');if (savedPos) {window.scrollTo(0, savedPos);}

来源:不秃头程序员

相关推荐