jQuery - 仅当顶部不可见时滚动到元素的顶部

jQuery - scrolling to the top of an element only if the top is not visible

假设我有一堆盒子,每个盒子的底部都有一个 "scroll to top" link。多亏了各种答案中发布的代码,我才能让滚动工作得很好:

<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/

但是,还有一件事我还需要做,那就是我被困的地方:我只想滚动,如果 top框不可见。 (准确地说,太高看不见了。)

我已经尝试了 this answer 中发布的代码 - 如果您取消对 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');
    }
});

Updated JS Fiddle Demo