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

2023-12-19

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

这是我的代码

<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 我不明白为什么会发生这种情况。

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/ 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何保存Jquery Mobile页面当前滚动位置的偏移量 的相关文章

随机推荐