在Scroll上捕捉Div/Element的顶部

cqd*_*qde 4 jquery scroll scrolltop

任何人都可以推荐一种"最佳"方法,在向下滚动页面时将滚动条捕捉到元素的顶部?

例如,如果我的布局如下:

<div id="section-one" style="width: 100%; height: 600px;">
    Section One
</div>

<div id="section-two" style="width: 100%; height: 600px;">
    Section Two
</div>

<div id="section-three" style="width: 100%; height: 600px;">
    Section Three
</div>

<div id="section-four" style="width: 100%; height: 600px;">
    Section Four
</div>
Run Code Online (Sandbox Code Playgroud)

如果用户正在查看第一部分并开始浏览第二部分开始参与浏览器视口,我希望浏览器自动捕捉到下一个div的顶部.

我熟悉.scroll()和.scrollTop,但有点不确定从哪里开始.

oca*_*nal 8

您可以使用@Scott Dowding创建的isScrolledIntoView函数检查元素是否在wiewport中,

这是一个例子,

$(document).scroll(function() {
    $("div:not(.highlight)").each(function() {
        if (isScrolledIntoView(this)) {
           $("div").removeClass("highlight");
           $(this).addClass("highlight");
           $("body").animate({ scrollTop: $(this).offset().top }, 1000)
        }
    });
});

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return (elemTop <= docViewBottom) && (elemTop > docViewTop);
}?
Run Code Online (Sandbox Code Playgroud)

DEMO