简体   繁体   English

如何将滚动条滚动到页面中心?

[英]How to scroll the scrollbar to the center of the page?

I am following this post. 我正在关注这篇文章。

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

I do like the answer but when I use it, I got an error in my console. 我确实喜欢这个答案,但是当我使用它时,控制台出现错误。

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

The error: 错误:

Uncaught TypeError: Cannot read property 'top' of undefined 未捕获的TypeError:无法读取未定义的属性“ top”

I am not sure why $(this).offset() is undefined . 我不确定为什么$(this).offset() is undefined Can anyone help me about it? 有人可以帮我吗?

Thanks! 谢谢!

Instead of using $(this) , use $('body').offset() instead. 而不是使用$(this) ,而是使用$('body').offset() Looks like $(this) is referring to the window object which has no offset property. 看起来$(this)指的是没有offset属性的window对象。

You need to mention what "this" stands for. 您需要提及“ this”代表什么。 In the post you mention, they are using the 'img' tag. 在您提到的帖子中 ,他们使用的是'img'标签。 Use this instead: 使用此代替:

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

Also, you might want to change the 5000 at the end to a smaller number. 另外,您可能希望将结尾的5000更改为较小的数字。 Else it will take 5 seconds to scroll to the center of the page. 否则,将需要5秒钟滚动到页面中心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM