如何使div跟随jQuery平滑滚动?
在我的容器中有节/框,但是当其他框都不可见时,这些框中的最后一个框应该跟随滚动 。
In my container there are sections/boxes, but the last one of these boxes should follow scrolling when none of the other boxes are visible.
因此,当用户向下滚动时,他会看到一个正常的侧边栏,但是当用户向下滚动时,侧边栏将结束,但最后一个框将出现在屏幕顶部。我在不同类型的网站上看到过很多。
So, when user scrolls down, he sees a normal sidebar, but when user has went down enough, sidebar ends but the last box starts to follow on the top of the screen. I have seen this a lot on different kind of sites.
我目前的代码:
$(window).scroll(function(){
$.each($('.follow-scroll'),function(){
var eloffset = $(this).offset();
var windowpos = $(window).scrollTop();
if(windowpos<eloffset.top) {
var finaldestination = 0;
} else {
var finaldestination = windowpos;
}
$(this).stop().animate({'top':finaldestination},200);
});
});
由于这个问题引起了很多关注,在投票最多的答案中链接的教程似乎处于脱机状态,我花了一些时间清理此脚本。
Since this question is getting a lot of views and the tutorial linked in the most voted answer appears to be offline, I took the time to clean up this script.
在此处实时查看: JSFiddle
See it live here: JSFiddle
JavaScript:
JavaScript:
(function($) {
var element = $('.follow-scroll'),
originalY = element.offset().top;
// Space between element and top of screen (when scrolling)
var topMargin = 20;
// Should probably be set in CSS; but here just for emphasis
element.css('position', 'relative');
$(window).on('scroll', function(event) {
var scrollTop = $(window).scrollTop();
element.stop(false, false).animate({
top: scrollTop < originalY
? 0
: scrollTop - originalY + topMargin
}, 300);
});
})(jQuery);