Scroll to element only if not in view - jQuery

前端 未结 10 1234
醉酒成梦
醉酒成梦 2020-12-13 18:26

I know a variation on this has been asked several times; I\'ve been browsing SO for a while now but either I\'m doing something wrong or I haven\'t found what I need.

<
10条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 18:54

    I modified the answer from @iandisme a bit and wrapped it up as a tiny jquery plugin:

    (function ($) {
    'use strict';
    
    $.fn.scrollToSimple = function ($target) {
        var $container = this.first();      // Only scrolls the first matched container
    
        var pos = $target.position(), height = $target.outerHeight();
        var containerScrollTop = $container.scrollTop(), containerHeight = $container.height();
        var top = pos.top + containerScrollTop;     // position.top is relative to the scrollTop of the containing element
    
        var paddingPx = containerHeight * 0.15;      // padding keeps the target from being butted up against the top / bottom of the container after scroll
    
        if (top < containerScrollTop) {     // scroll up                
            $container.scrollTop(top - paddingPx);
        }
        else if (top + height > containerScrollTop + containerHeight) {     // scroll down
            $container.scrollTop(top + height - containerHeight + paddingPx);
        }
    };
    })(jQuery);
    

    I removed the calls to .animate since I was looking for instant scrolling. I also added the ability to scroll any (scrollable) container, rather than just the window. Example usage:

    // scroll the window so #target  is visible
    $(window).scrollToSimple( $("#target") );
    
    // scroll the scrollable element #container so that #target is visible
    $("#container").scrollToSimple( $("#target") );
    

提交回复
热议问题