2016-08-02 56 views
0

我想在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

回答

0

彼時使用會話存儲。有用,但並不美觀,因爲它在頁面加載時從頂部開始,並且在單擊鏈接之前立即跳轉到您所在的位置。

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

但這似乎也不適用於手機。 – LearntoExcel

+0

如果有人知道我爲什麼會接受這個答案 – LearntoExcel

1

我認爲問題是,你保存在一個局部變量,其消失的位置當你加載新的頁面。

您需要某種方法將滾動頂端值傳遞到新頁面。我建議使用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