0

我对 .scrollTop() 有疑问

我有一个页面在卸载时存储会话中的当前 scrollTop() 位置。我的目标是当我回到这个页面时,页面滚动到我在它上面的最后一个 scrollTop 位置。

我的 JS 代码很简单:

console.log('=>'+parseInt(scrollto)+' '+parseInt($(window).scrollTop())); 
$(window).scrollTop(scrollto);
console.log('=>'+parseInt(scrollto)+' '+parseInt($(window).scrollTop()));

结果在我的浏览器控制台中:

=> 2500 0
=> 2500 2500

好的,我的页面滚动到最后一个位置。

问题来自scrollto 变量的大值。这就是我在控制台中得到的:

=> 12352 0
=> 12352 7683

我不明白为什么它没有在请求的位置滚动

我什至试过这个:

var max_times= 10;

for(var i=0;i<max_times;i++){
console.log('=>'+parseInt(scrollto)+' '+parseInt($(window).scrollTop()));
if (parseInt(scrollto) > parseInt($(window).scrollTop())) 
    $(window).scrollTop(scrollto);
}

结果:

=> 13450 0
=> 13450 7985
=> 13450 7985
=> 13450 7985
...
=> 13450 7985

其他信息:

  • 我在 Chrome 和 Safari 上的结果相同。
  • 我正在谈论的页面包含很多图像,因此完全加载需要一些时间。

我真的很感激任何帮助。

谢谢你。

4

2 回答 2

0

@lalibi has a good point in asking if the images have a height set, if you are asking to scroll to 13450 but at the current time the page height is less than 13450px then something is not going to work correctly. If you try setting a timeout to the scrollTop to when all the images have loaded, does it still fail? If you notice that it doesn't then you will have to either load the images in a way where once all is loaded then execute the scrollTop or set the images height so that page knows exactly how tall it is.

于 2011-11-21T16:23:24.833 回答
0

好的。

我找到了一个可行的解决方案。

感谢您的提示,必须涉及页面的总高度。

我所做的是:

var timer = setInterval(function(){
    if ((parseInt(scrollto) > parseInt($(window).scrollTop())) && (parseInt($(document).height())>parseInt(scrollto))){
       $(window).scrollTop(scrollto);
       if ($(window).scrollTop()>=scrollto)
           clearInterval(timer);    
    }
},500);

setTimeout(function(){clearInterval(timer);},10000);

我设置了一个间隔来检查页面的总高度是否足以每 500 毫秒滚动到请求的位置。如果是这种情况,它会滚动。如果位置OK,那么我们清除区间。

如果这些都不起作用,则间隔将在 10 秒后清除。

再次感谢您帮助我解决这个问题!

于 2011-11-22T14:26:10.513 回答