Scroll to the center of viewport

后端 未结 4 1830
南笙
南笙 2021-01-31 12:18

I would like to center a div by clicking it. So if I\'m clicking a div I want it to scroll to the center of the browser viewport. I don\'t want to use

4条回答
  •  庸人自扰
    2021-01-31 12:44

    In some way you have to identify the clickable elements. I build an example, that uses the class-attribute for that.

    Step 1

    This is the script, that does the work:

    $('html,body').animate({
        scrollTop: $(this).offset().top - ( $(window).height() - $(this).outerHeight(true) ) / 2
    }, 200);
    

    What you tried is to scroll the container to the top of the page. You also have to calculate and subtract the difference between the container height and the viewport height. Divide this by two (as you want to have the same space on top and bottom and you are ready to go.

    Step 2

    Then you add the click handler to all the elements:

    $(document).ready(function () {
        $('.image').click( function() {
            $('html,body').animate({ scrollTop: $(this).offset().top - ( $(window).height() - $(this).outerHeight(true) ) / 2  }, 200);
        });
    });
    

    Step 3

    Set up some HTML/CSS:

    
    
    
    1
    2
    3
    4
    5

    And you're done.

    Check out the demo

    Try it yourself http://jsfiddle.net/insertusernamehere/3T9Py/

提交回复
热议问题