Scroll to the center of viewport

£可爱£侵袭症+ 提交于 2019-12-03 05:21:39

问题


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 anchor points like the guides and examples I've seen. How can I achieve this?


回答1:


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:

<style>

    div.image {

        border:     1px solid red;
        height:     500px;
        width:      500px;
    }

</style>

<div class="image">1</div>
<div class="image">2</div>
<div class="image">3</div>
<div class="image">4</div>
<div class="image">5</div>

And you're done.

Check out the demo

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




回答2:


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);
}



回答3:


HTMLElement.prototype.scrollToCenter = function(){
    window.scrollBy(0, this.getBoundingClientRect().top - (window.innerHeight>>1));
}

Achieved with pure JavaScript for Scrolling to Center in the vertical direction. And it's similar in the horizontal direction. I don't take elements' height into consideration, because they maybe larger than the height of screen.



来源:https://stackoverflow.com/questions/11529070/scroll-to-the-center-of-viewport

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!