How to make div follow scrolling smoothly with jQuery?

后端 未结 10 2361
我寻月下人不归
我寻月下人不归 2020-11-28 19:24

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 sc

10条回答
  •  温柔的废话
    2020-11-28 19:33

    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.

    See it live here: JSFiddle

    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);
    

提交回复
热议问题