[英]Jquery scrollTop always scrolling to top of page, NOT top of element found
[英]jQuery - scrolling to the top of an element only if the top is not visible
假設我有一堆盒子,每個盒子的底部都有一個“ scroll to top”鏈接。 多虧了在各種答案中發布的代碼,我才能夠很好地實現滾動:
<div class="box" style="height: 500px;">
<p>some tall box</p>
<span class="scroll-link">scroll to top of box</span>
</div>
$('.scroll-link').on('click', function () {
var $parent = $(this).parent();
$('html, body').animate({
scrollTop: $parent.offset().top
}, 'slow');
});
http://jsfiddle.net/L1d394ev/5/
但是,我仍然需要做一件事,這就是我要堅持的地方: 我只想在框頂部不可見的情況下滾動 。 (准確地說, 太高了以至於看不見。)
我已經嘗試過此答案中發布的代碼-如果您取消注釋if
,這在我的JSfiddle中很明顯-但這似乎完全禁用了滾動。
我想我需要做的是檢查元素的頂部是否太高而看不見,但是我不知道該怎么做。
您的問題是計算偏移量的方式:
$('.scroll-link').on('click', function () {
var $parent = $(this).parent();
// Get the offset alone
var offset = $parent.offset().top;
// If the offset is less than the scroll position
if (offset < $(window).scrollTop()) {
$('html, body').animate({
// reuse your 'offset' variable instead of calculating it again
scrollTop: offset
}, 'slow');
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.