Scroll to the center of viewport

后端 未结 4 1824
南笙
南笙 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条回答
  •  梦毁少年i
    2021-01-31 12:37

    I've got one slight modification to offer.
    If the "adjustment factor" i.e. ( $(window).height() - $(this).outerHeight(true) ) / 2 is < 0 you can get undesirable results whereby you overshoot that element in the viewport with your scroll.

    I added a max(0,adjustment factor) to correct :

        function scrollIntoView(el) {
        
            var offsetTop = $j(el).offset().top;
            var adjustment = Math.max(0,( $j(window).height() - $j(el).outerHeight(true) ) / 2);
            var scrollTop = offsetTop - adjustment;
        
            $j('html,body').animate({
                scrollTop: scrollTop
            }, 200);
        }
    

提交回复
热议问题