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

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

    Since you want to know how it works, I'll explain it step-by-step.

    First you want to bind a function as the image's click handler:

    $('#someImage').click(function () {
        // Code to do scrolling happens here
    });
    

    That will apply the click handler to an image with id="someImage". If you want to do this to all images, replace '#someImage' with 'img'.

    Now for the actual scrolling code:

    1. Get the image offsets (relative to the document):

      var offset = $(this).offset(); // Contains .top and .left
      
    2. Subtract 20 from top and left:

      offset.left -= 20;
      offset.top -= 20;
      
    3. Now animate the scroll-top and scroll-left CSS properties of and :

      $('html, body').animate({
          scrollTop: offset.top,
          scrollLeft: offset.left
      });
      

提交回复
热议问题