如何使 div 跟随 jQuery 平滑滚动? [英] How to make div follow scrolling smoothly with 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);
这篇关于如何使 div 跟随 jQuery 平滑滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!