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

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

    There's a DOM method called scrollIntoView, which is supported by all major browsers, that will align an element with the top/left of the viewport (or as close as possible).

    $("#myImage")[0].scrollIntoView();
    

    On supported browsers, you can provide options:

    $("#myImage")[0].scrollIntoView({
        behavior: "smooth", // or "auto" or "instant"
        block: "start" // or "end"
    });
    

    Alternatively, if all the elements have unique IDs, you can just change the hash property of the location object for back/forward button support:

    $(document).delegate("img", function (e) {
        if (e.target.id)
            window.location.hash = e.target.id;
    });
    

    After that, just adjust the scrollTop/scrollLeft properties by -20:

    document.body.scrollLeft -= 20;
    document.body.scrollTop -= 20;
    

提交回复
热议问题