【问题标题】:How to scroll the scrollbar to the center of the page?如何将滚动条滚动到页面中心?
【发布时间】:2014-02-05 01:49:36
【问题描述】:

我正在关注这篇文章。

Scroll to the center of viewport

我确实喜欢这个答案,但是当我使用它时,我的控制台出现错误。

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

错误:

未捕获的类型错误:无法读取未定义的属性“顶部”

我不知道为什么$(this).offset() is undefined。谁能帮帮我?

谢谢!

【问题讨论】:

  • 我没有收到任何错误

标签: javascript jquery css


【解决方案1】:

不要使用$(this),而是使用$('body').offset()。看起来$(this) 指的是没有偏移属性的窗口对象。

【讨论】:

  • 有趣,当 OP 在外部调用中明确使用 $('body') 时,这怎么可能?
  • 我查看了一下 jQuery 源代码,似乎动画是在窗口上下文中使用 setTimeout 而不是选择器运行的,虽然我可能错了,但它是一个非常复杂的库一步通过。不过,情况似乎确实如此。
  • 我想我明白了,这是因为对$(this) 的调用不在函数内部,所以这是window。当您将函数传递给 $.on 时,我在想,在其中,这是当前元素
【解决方案2】:

您需要提及“this”代表什么。在您提到的post 中,他们使用的是“img”标签。改用这个:

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

此外,您可能希望将末尾的 5000 更改为较小的数字。否则滚动到页面中心需要 5 秒钟。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    相关资源
    最近更新 更多