[英]How to scroll the scrollbar to the center of the page?
我正在關注這篇文章。
我確實喜歡這個答案,但是當我使用它時,控制台出現錯誤。
$('body').animate({
scrollTop: $(this).offset().top - ($(window).height()-$(this).outerHeight(true)) / 2
}, 5000);
錯誤:
未捕獲的TypeError:無法讀取未定義的屬性“ top”
我不確定為什么$(this).offset() is undefined
。 有人可以幫我嗎?
謝謝!
而不是使用$(this)
,而是使用$('body').offset()
。 看起來$(this)
指的是沒有offset屬性的window對象。
您需要提及“ this”代表什么。 在您提到的帖子中 ,他們使用的是'img'標簽。 使用此代替:
$( document ).ready(function() {
$('body').animate({ scrollTop: $('body').offset().top - ( $(window).height() - $(this).outerHeight(true) ) / 2 }, 500);
});
另外,您可能希望將結尾的5000更改為較小的數字。 否則,將需要5秒鍾滾動到頁面中心。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.