简体   繁体   English

回到历史记录时,Sammy.js缓存并滚动位置

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

I don't know if anyone is still using Sammy.js, but I found it perfectly suits my needs for a lightweight routing and templating library. 我不知道是否有人仍在使用Sammy.js,但我发现它非常适合我对轻量级路由和模板库的需求。 If anyone has other ideas, please let me know. 如果有人有其他想法,请告诉我。

My problem is that when I have a long page and I scroll down, click on a link on this page and go back, the whole page is reloaded (in Sammy, the GET route is called) and it jumps to the top of the page. 我的问题是,当我有一个长页面并向下滚动时,单击此页面上的链接然后返回,重新加载整个页面(在Sammy中,调用GET路由)并跳转到页面顶部。

My question is: Is there a way to have Sammy cache the page and maintain the scroll position when going back in the history? 我的问题是:有没有办法让Sammy缓存页面并在回到历史记录时保持滚动位置?

Thanks in advance. 提前致谢。

You could use localStorage as alternative way to store url-scrolltop as a pair. 您可以使用localStorage作为将url-scrolltop存储为一对的替代方法。 This way the browser remembers srolltop position for the specified url. 这样浏览器会记住指定网址的srolltop位置。

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 example JSbin的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM