Hi FE !
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
  • 记录上次位置

记录上次位置

1. 节流函数

// 节流函数:限制滚动事件的触发频率
function throttle(func, delay) {
  let lastCall = 0; // 上次触发的时间
  return function (...args) {
    const now = new Date().getTime();
    if (now - lastCall >= delay) {
      // 如果距离上次触发已经超过指定时间
      lastCall = now;
      func.apply(this, args); // 执行函数
    }
  };
}

2. 核心逻辑

const pageKey = window.location.href;

// 监听滚动事件,保存滚动位置(带节流)
window.addEventListener(
  "scroll",
  throttle(() => {
    const scrollPosition = window.scrollY;
    localStorage.setItem(pageKey, scrollPosition); // 保存滚动位置
    localStorage.setItem(`${pageKey}_timestamp`, Date.now()); // 记录时间戳
  }, 300)
); // 每300毫秒保存一次滚动位置

// 页面加载时恢复滚动位置
window.addEventListener("load", () => {
  const savedScrollPosition = localStorage.getItem(pageKey);
  if (savedScrollPosition !== null) {
    window.scrollTo({
      top: parseInt(savedScrollPosition),
      behavior: "smooth", // 平滑滚动
    });
  }

  // 清理过期数据
  cleanOldScrollPositions();
});

3. 清理过期数据函数

function cleanOldScrollPositions() {
  const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000; // 计算7天前的时间戳

  for (let key of Object.keys(localStorage)) {
    if (key.endsWith("_timestamp")) {
      // 只处理带有时间戳的键
      const timestamp = localStorage.getItem(key);
      if (parseInt(timestamp) < sevenDaysAgo) {
        // 如果时间戳超过7天
        const baseKey = key.replace("_timestamp", "");
        localStorage.removeItem(baseKey); // 删除滚动位置数据
        localStorage.removeItem(key); // 删除时间戳数据
      }
    }
  }
}
Edit this page
最近更新: 2025/6/27 02:24
Contributors: qdleader
qdleader
本站总访问量 129823次 | 本站访客数 12人