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

后端 未结 11 1347
夕颜
夕颜 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:18

    Just a tip. Works on firefox only

    Element.scrollIntoView();

    0 讨论(0)
  • 2020-11-28 20:23

    Here's a quick jQuery plugin to map the built in browser functionality nicely:

    $.fn.ensureVisible = function () { $(this).each(function () { $(this)[0].scrollIntoView(); }); };
    
    ...
    
    $('.my-elements').ensureVisible();
    
    0 讨论(0)
  • 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 });
    }
    
    0 讨论(0)
  • 2020-11-28 20:28

    Have a look at the jQuery.scrollTo plugin. Here's a demo.

    This plugin has a lot of options that go beyond what native scrollIntoView offers you. For instance, you can set the scrolling to be smooth, and then set a callback for when the scrolling finishes.

    You can also have a look at all the JQuery plugins tagged with "scroll".

    0 讨论(0)
  • 2020-11-28 20:33

    There are methods to scroll element directly into the view, but if you want to scroll to a point relative from an element, you have to do it manually:

    Inside the click handler, get the position of the element relative to the document, subtract 20 and use window.scrollTo:

    var pos = $(this).offset();
    var top = pos.top - 20;
    var left = pos.left - 20;
    window.scrollTo((left < 0 ? 0 : left), (top < 0 ? 0 : top));
    
    0 讨论(0)
提交回复
热议问题