【问题标题】:Scroll to the center of viewport滚动到视口中心
【发布时间】:2012-07-17 19:00:08
【问题描述】:

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

【问题讨论】:

  • $('html,body').animate({ scrollTop: $("#divToBeScrolledTo").offset().top; });我不想指定它是什么 div 。我想将 div 居中点击。因此,如果我正在浏览图片,我想将图片放在浏览器视口中。而且因为人们可以添加自己的图片,手动添加锚点并不方便:)
  • 当然你需要指定你想要滚动到哪个div。你不知道你想要居中吗?
  • 哈哈,当然!但我不能喜欢 ScrollTo('this') 之类的吗?
  • 否,因为字符串“this”不是有效的选择器。阅读 the docs 了解 jQuery 构造函数能够处理的内容。
  • 那么,如果我得到“随机”的 id,我该如何去除选择器和对象? :)

标签: javascript jquery scroll center scrollto


【解决方案1】:

您必须以某种方式识别可点击元素。我构建了一个示例,它为此使用了class-attribute。

步骤 1

这是执行工作的脚本:

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

您尝试将容器滚动到页面顶部。您还必须计算并减去容器高度和视口高度之间的差值。将其除以二(因为您希望顶部和底部具有相同的空间,您就可以开始了。

第二步

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

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

第三步

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

【讨论】:

  • insertusername这里你真是个神!谢谢!
【解决方案2】:
HTMLElement.prototype.scrollToCenter = function(){
    window.scrollBy(0, this.getBoundingClientRect().top - (window.innerHeight>>1));
}

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

【讨论】:

  • 您能解释一下为什么在这里使用“>>”(右移)运算符吗?
【解决方案3】:

我知道这个问题很老了,但现在,你可以使用scrollIntoView

例如:

document.body.scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'center' });

【讨论】:

  • 很遗憾,它不适用于旧版浏览器。
【解决方案4】:

我要提供一点修改。
如果“调整因子”,即( $(window).height() - $(this).outerHeight(true) ) / 2&lt; 0,您可能会得到不希望的结果,即您在滚动时会超出视口中的该元素。

我添加了一个max(0,adjustment factor) 来更正:

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

【讨论】:

  • @insertusernamehere 但是这样如果元素大于窗口高度,它将完全可见,而不是居中,但从一开始就可见,这就像“居中直到它不适合,然后只需将视图滚动到元素开始“
  • @Programista 啊,谢谢你说清楚。现在我明白了“overshoot”的含义。根据用例(真正居中或居中,如果适用),这是另一种解决方案,这里是fiddle to demonstrate it
  • 非常感谢..根据我的需要对其进行了优化..像魅力一样工作 =)
  • 在 Vanilla JavaScript 中会是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-04
  • 2019-09-25
  • 2018-12-17
  • 1970-01-01
  • 2019-02-06
  • 1970-01-01
相关资源
最近更新 更多