单击保存滚动位置,然后检索? [英] Save scroll position on click and then retrieving?

查看:208
本文介绍了单击保存滚动位置,然后检索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

还可以使其兼容移动设备(iOS,Android等)的任何人的奖励积分:)

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

推荐答案

使用会话存储完成工作.可以,但是效果不佳,因为页面加载时从顶部开始,并立即跳转到您在单击链接之前的位置.

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

这篇关于单击保存滚动位置,然后检索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆