如何为Jquery Mobile页面保存当前滚动位置的偏移量

我试图在全局变量中保存页面当前值的偏移量,并尝试在重新加载页面时使用它来滚动回相同的位置。

这是我的代码

 $(document).on("pagebeforeshow", '#outerPage', function(){ $(document).on('vclick','#outerPage',function(e){ //alert('yo i am clickable now'); var parentOffset = $(this).parent().offset(); //or $(this).offset(); if you really just want the current element's offset var relX = e.pageX - parentOffset.left; var relY = e.pageY - parentOffset.top; storePosition.topCoordinate = relY; }); var positionY = storePosition.topCoordinate ; if(positionY !== null) { setTimeout(function () { $.mobile.defaultHomeScroll = positionY; }, 10); } }); var storePosition = { topCoordinate : null }  

这里我试图在storePosition.topCoordinate存储偏移量,然后在函数中使用它来设置页面滚动。 但我的变量总是设置为null我不明白为什么会发生这种情况。

UPDATE

现在我正在使用这样的脚本

 $(document).on('pageinit', '#outerPage', function () { $('a').on('vclick', function () { console.log('its done Boy'); localStorage.setItem('scrolls', 0); }); }); /*$(window).on('unload', function() { console.log(window.location.pathname); console.log(window.location.pathname); console.log( "Bye now!" ); })*/ $(document).on('pageinit', '#outerPage', function () { $(document).on("scrollstop", function () { var parentOffset = $(this).parent().offset(); var relY = window.scrollY; localStorage.setItem('scrolls', relY); console.log(localStorage.getItem("scrolls")); }); }); $(document).on("pagebeforeshow", '#outerPage', function () { var positionY = localStorage.getItem("scrolls"); if (positionY != null) { $.mobile.defaultHomeScroll = positionY; } }); 

所以我在localStorage中保存值并在我更改页面时将其清除,就像我点击链接标签时一样,我知道这不是正确的解决方案:P。 我试图使用.unload()但是当刷新同一页面时它没有清除LocalStorage事件

这个你能帮我吗

感谢和问候

在我的一个项目中,我使用此代码记住页面上的最后一个滚动位置。

演示(只需在列表上滚动,到第2页然后再回来)

http://jsfiddle.net/ukzuvtyh/

用于remmebring最后位置的Jquery代码

 var storePosition = { /// initializing the storeposition topCoordinate : null } storePosition.topCoordinate = $(this).offset().top; /// storing the position if(storePosition.topCoordinate !== 0) { // if we are at the top no point doing anything $("html, body").animate({"scrollTop": storePosition.topCoordinate}, 500); } 

如果您在返回某些页面时看到滚动到最后一个位置,则按一些像素减去或添加以获得确切位置。 之后会好的。 你需要在适量之前做出判断。 – 60在滚动上显示60像素减去。 我有这个问题,不知道为什么这么一个问题

 $("html, body").animate({"scrollTop": storePosition.topCoordinate - 60}, 500);