2012-08-31 128 views
1

所以我有一个垂直滚动网站的'网页'的方式。当用户停止滚动时,我希望浏览器对齐浏览最多的页面。jQuery动画页面捕捉循环滚动结束

我有一个方法来找到哪个元素是inview,并使用一个简单的插件我有一个事件,当滚动停止时触发。

我遇到的问题是如何正确使用它。

我使用浏览器动画滚动到滚动停止处的inview页面的顶部。然而,这会启动另一个滚动并重新启动一切,导致一些奇怪的不断滚动的错误并导致它在页面中跳跃。

有没有人有任何不同的方式来实现这一点,以避免循环的想法?我现在真的很困难。

下面的代码。并感谢您的任何建议。

$(window).bind('scrollstop', function(e){ 

//this grabs the ID of the div containing my h1 element. This is how I decide which 'page' is inview 
var inview = '#' + $('.section-header:in-viewport:first').parent().parent().attr('id'); 

//then I grab the distance from the top, so that it can be scrolled to 
var this_pos = $(inview).offset().top; 

//finally I animate the page to scroll to the top of the inview element. 
$('html > body').animate({'scrollTop' : this_pos}, 200).delay(1000); 


}); 

回答

0

所以最后我解决了这个问题,在滚动结束时为函数触发添加了一个延迟。 100ms的延迟足以防止它过早发射并在不需要时用滚动调整页面。这导致了页面上的无限循环和怪异。

这是我的最终代码:

$(window).bind('scrollstop', function(e){ 

    var inview = '#' + $('.section-header:in-viewport:first').parent().parent().attr('id'); 
    var this_pos = $(inview).offset().top;  

    //animate to the top of the .page, with a 200 delay 
    $('html > body').animate({'scrollTop' : this_pos}, 200); 


    //a delay of 100 here is enough to stop a scrollend loop starting causing weirdness. 
     }).delay(100); 
1

这样的事情,也许呢?

$('body').animate({ 
    scrollTop: inview.offset().top - $('body').offset().top + $('body').scrollTop() 
});​ 
+0

这是没有任何影响。根本没有滚动(滚动结束)。 (除非我把它放在错误的地方?我只是取代了整个'动画'行... – josh

+0

好吧,因为我不知道你的整个代码是什么样的,看看scrollTop文档,也许它会引导你朝着正确的方向前进:http://api.jquery.com/scrollTop/ –

+0

你能解释一下背后的逻辑吗?inview offset减去体偏移量(大概是0?),再加上body scrolltop(0也是?)。应该说,这不是页面动画的问题,它会在每次滚动结束时触发,然后它滚动到位置,然后再次触发它,从而引发一个循环。 – josh