javascript – 滚动到视口的中心

我想通过点击它来集中一个div.所以如果我点击一个div我想要滚动到浏览器视口的中心.我不想使用锚点,像我看过的指南和例子.我该如何实现?

解决方法

在某种程度上,您必须确定可点击的元素.我构建一个例子,它使用类属性.

步骤1

这是脚本,做的工作:

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

您尝试的是将容器滚动到页面顶部.您还必须计算和减去容器高度和视口高度之间的差异.把它分成两个(你想要在顶部和底部有相同的空间,你准备好了.

第2步

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

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

步骤3

设置一些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/

相关文章

kindeditor4.x代码高亮功能默认使用的是prettify插件,prett...
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小