Save scroll position on click and then retrieving?

2019-09-14 03:11发布

问题:

I am trying to write a function in jquery that when a button is clicked, the user's scroll position is saved, and then when the page loads the link that the button directed to, the scroll position is retrieved. Here is my function. I am not sure what the problem is as I am relatively new to this.

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
});

Bonus points for anyone who can also make it mobile (ios, Android, etc.) compatible :)

回答1:

I believe the issue is that you're saving the position in a local variable which disappears when you load the new page.

You need some way of passing the scroll top value to the new page. I suggest using the url hash - see https://developer.mozilla.org/en-US/docs/Web/API/Window/location#Example_3

So on click: window.location = href + '#' + scrollTop; (note: if any of your links already have a hash, like my link above, you'll need to do a more complicated approach for merging the scrollTop with the old hash, and splitting them up on the other end)

On load: var scrollTop = window.location.hash;



回答2:

Wound up using session storage. Works but is not pretty as it starts out at the top when the page loads and immediately jumps to where you were before clicking the link.

$(document).ready(function(){
 $('a.page-numbers').click(function(){
  sessionStorage["scrollPosition"] = $(window).scrollTop();
 });
 $(window).scrollTop(sessionStorage["scrollPosition"]);
   sessionStorage.clear();
});