How do I get an element to scroll into view, using jQuery?

后端 未结 11 1396
夕颜
夕颜 2020-11-28 19:31

I have an HTML document with images in a grid format using

  • . The browser window has both vertical & horizontal scrolling.

11条回答
  •  隐瞒了意图╮
    2020-11-28 20:26

    After trial and error I came up with this function, works with iframe too.

    function bringElIntoView(el) {    
        var elOffset = el.offset();
        var $window = $(window);
        var windowScrollBottom = $window.scrollTop() + $window.height();
        var scrollToPos = -1;
        if (elOffset.top < $window.scrollTop()) // element is hidden in the top
            scrollToPos = elOffset.top;
        else if (elOffset.top + el.height() > windowScrollBottom) // element is hidden in the bottom
            scrollToPos = $window.scrollTop() + (elOffset.top + el.height() - windowScrollBottom);
        if (scrollToPos !== -1)
            $('html, body').animate({ scrollTop: scrollToPos });
    }
    

提交回复
热议问题