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

问题描述:

我想在jquery中写一个函数,当单击一个按钮时,用户的滚动位置被保存,然后当页面加载按钮指向的链接时,滚动位置被检索。这是我的功能。我不确定是什么问题,因为我相对比较新。点击保存滚动位置,然后检索?

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等)兼容:)

+0

变量或任何JavaScript,只是**不**持续跨页面加载。您需要持久存储。 – adeneo

+0

我可以问你想要什么类型的永久存储? – LearntoExcel

+0

那么,任何可以存储这些值直到下一页加载的持久性存储。本地存储,Cookie,使用URL或服务器来存储值等 – adeneo

彼时使用会话存储。有用,但并不美观,因为它在页面加载时从顶部开始,并且在单击链接之前立即跳转到您所在的位置。

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

但这似乎也不适用于手机。 – LearntoExcel

+0

如果有人知道我为什么会接受这个答案 – LearntoExcel

我认为问题是,你保存在一个局部变量,其消失的位置当你加载新的页面。

您需要某种方法将滚动顶端值传递到新页面。我建议使用url哈希 - 看https://developer.mozilla.org/en-US/docs/Web/API/Window/location#Example_3

于是就点击window.location = href + '#' + scrollTop;(注意:如果您的任何链接已经有一个哈希,就像我上面的链接,你就需要为合并做一个更复杂的方法该scrollTop的与旧的哈希,并分割了他们在另一端)

在负载var scrollTop = window.location.hash;

+0

我正在使用这些函数与分页,所以哈希不断变化。那么上述方法仍然有益吗? – LearntoExcel

+0

当然,请参阅我关于已经有哈希链接的注释 - 您只需在加载新页面之前将哈希位置添加到哈希中,并在加载新页面后从哈希中删除位置 – alexanderbird

+0

欣赏帮助,但伤口了解如何使用会话存储。 – LearntoExcel