单击保存滚动位置然后检索?

Save scroll position on click and then retrieving?

我正在尝试在 jquery 中编写一个函数,当单击按钮时,将保存用户的滚动位置,然后当页面加载按钮指向的 link 时,检索滚动位置。这是我的功能。我不确定是什么问题,因为我对此比较陌生。

var scrolltop;

$(document).ready(function(){
 $('a.page-numbers').click(function() {
  scrolltop = $(document).scrollTop(); // store it
  var href = $(this).attr('href'); 
  window.location= href; // I am doing this to force a button to go to a link and temporarily fix a pagination issue if people are curious.  Not the current issue at hand.
  return false; // Doing this so page doesn't scroll on click
 });
});

$(document).ready(function(){
 $('html, body').animate({scrollTop: scrolltop}); //not scrolling to where saved
});

任何人都可以使其移动(ios、Android 等)兼容的奖励积分:)

我认为问题在于您将位置保存在局部变量中,当您加载新页面时该变量会消失。

您需要某种方式将滚动顶部值传递到新页面。我建议使用 url 散列 - 参见 https://developer.mozilla.org/en-US/docs/Web/API/Window/location#Example_3

所以点击window.location = href + '#' + scrollTop;(注意:如果你的link中的任何一个已经有了哈希,就像我上面的link ,你需要做一个更复杂的方法来合并 scrollTop 和旧的散列,并在另一端将它们分开)

加载中var scrollTop = window.location.hash;

结束使用会话存储。有效但不漂亮,因为它在页面加载时从顶部开始,并立即跳转到您在单击 link.

之前所在的位置
$(document).ready(function(){
 $('a.page-numbers').click(function(){
  sessionStorage["scrollPosition"] = $(window).scrollTop();
 });
 $(window).scrollTop(sessionStorage["scrollPosition"]);
   sessionStorage.clear();
});