Sammy.js缓存和滚动位置时,返回历史

Sammy.js cache and scroll position when going back in history

本文关键字:返回 历史 位置 滚动 js 缓存 Sammy      更新时间:2023-09-26

我不知道是否有人还在使用Sammy.js,但我发现它非常适合我对轻量级路由和模板库的需求。如果有人有其他想法,请告诉我。

我的问题是,当我有一个长页面,向下滚动时,单击该页面上的链接并返回,整个页面被重新加载(在Sammy中,调用GET路由),然后跳到页面顶部。

我的问题是:有没有办法让萨米缓存页面并在返回历史时保持滚动位置?

提前谢谢。

您可以使用localStorage作为将url scrolltop存储为一对的替代方法。这样,浏览器就会记住指定url的滚动停止位置。

var scroltop,url;
$(window).scroll(function() {
    scroltop = $(this).scrollTop();
    url = window.location.href;
    clearTimeout($.data(this, 'scrollTimer'));
    $.data(this, 'scrollTimer', setTimeout(function() {
    localStorage.setItem(url,scroltop);
    }, 250));
});
if(localStorage.getItem(window.location.href)) {
  url = window.location.href;
  scroltop = localStorage.getItem(url);
  $(window).scrollTop(scroltop);   
}

JSbin示例