滚动到视口中心

Des*_*non 11 javascript jquery scroll center scrollto

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

ins*_*ere 23

在某种程度上,您必须识别可点击元素.我构建了一个示例,它使用class-attribute.

步骤1

这是完成工作的脚本:

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

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

第2步

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

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

第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>
Run Code Online (Sandbox Code Playgroud)

而且你已经完成了.

看看演示

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


KBe*_*Dev 6

我知道这个问题已经很老了,但是现在,您可以使用scrollIntoView

例如:

document.body.scrollIntoView({
  behavior: 'smooth',
  inline: 'center',
  block: 'center'
});
Run Code Online (Sandbox Code Playgroud)


小智 5

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

使用纯 JavaScript 实现垂直方向滚动到中心。在水平方向上也是类似的。我不考虑元素的高度,因为它们可能大于屏幕的高度。

  • 您能解释一下为什么在这里使用“&gt;&gt;”(右移)运算符吗? (2认同)