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

时间:2014-09-25 10:53:26

标签: javascript jquery jquery-mobile

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

这是我的代码

<script>
$(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
}
</script>

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

更新

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

$(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事件

请帮我解决这个问题

谢谢&amp;此致

1 个答案:

答案 0 :(得分:3)

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

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

http://jsfiddle.net/ukzuvtyh/

用于记忆最后位置的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);