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

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

本文关键字:元素 顶部 滚动 jQuery      更新时间:2023-09-26

假设我有一堆框,每个框的底部都有一个"滚动到顶部"链接。多亏了各种答案中发布的代码,我才能让滚动工作得很好:

<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');
    }
});

更新的 JS 小提琴演示