滚动到视口中心 [英] Scroll to the center of viewport

查看:95
本文介绍了滚动到视口中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过点击它来居中 div 。因此,如果我点击 div ,我希望它滚动到浏览器视口的中心。我不想像我看到的指南和例子那样使用锚点。我怎样才能做到这一点?

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?

推荐答案

在某种程度上,你必须识别可点击的元素。我构建了一个示例,它使用 - 属性。

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

这是完成工作的脚本:

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

您尝试将容器滚动到页面顶部。您还必须计算和减去容器高度和视口高度之间的差异。将其除以2(因为你想在顶部和底部有相同的空间,你准备好了。

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.

然后将点击处理程序添加到所有元素:

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



第3步



设置一些HTML / CSS:

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>

你已经完成了。

自己尝试 http://jsfiddle.net/insertusernamehere / 3T9Py /

这篇关于滚动到视口中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆