Jquery 100%滚动到第一节



我试图滚动100%的页面到第一部分,然后有正常的滚动通过其他部分,反之亦然。

我尝试过不同的方法,除了循环没有结果。检查这个小提琴

这是页面的结构,每个元素都有100%的高度:

<header>Header content...</header>
<section>Section content...</section>
<section>Section content...</section>
<section>Section content...</section>
Javascript

$(function () {
    var lastScrollTop = $(window).scrollTop(),
        delta = 5,
        eleH = $('header').outerHeight();
    $(window).scroll(function () {
        var nowScrollTop = $(this).scrollTop();
        if (Math.abs(lastScrollTop - nowScrollTop) >= delta) {
            if (nowScrollTop <= eleH && nowScrollTop > lastScrollTop) {
                $('html,body').animate({
                    scrollTop: $('body section:first-of-type').offset().top
                }, 600);
                console.log('Scroll down');
            } else if (nowScrollTop <= eleH && nowScrollTop < lastScrollTop) {
                $('html,body').animate({
                    scrollTop: 0
                }, 600);
                console.log('Scroll up');
            }
            lastScrollTop = nowScrollTop;
        }
    });
});
CSS

html, body {
    height:100%
}
header, section {
    display:block;
    width:100%;
    height:100%;
}
header {
    background-color:gray;
}

作为插件,我已经使用了Alton(演示链接在小提琴),但它不能很好地工作,如果强调或与osX的惯性滚动。

要做到这一点,我添加了一个变量isScrolling,它表明javascript是否忙于做滚动。当scroll函数完成后,我将该变量设置为false,并重新计算lastScrollTop

JSFiddle

$(function () {
    var lastScrollTop = $(window).scrollTop(),
        delta = 5,
        eleH = $('header').outerHeight(),
        isScolling = false ;
    $(window).scroll(function () {
        if(isScolling)
            return;
        var nowScrollTop = $(this).scrollTop();
        if (Math.abs(lastScrollTop - nowScrollTop) >= delta) {
            if (nowScrollTop <= eleH && nowScrollTop >= lastScrollTop) {
                isScolling = true;
                $('html,body').animate({
                    scrollTop: $('body section:first-of-type').offset().top
                }, 600, function() {
                    isScolling = false;
                    lastScrollTop = $(window).scrollTop();
                });
                console.log('Scroll down');
            } else if (nowScrollTop <= eleH && nowScrollTop < lastScrollTop) {
                isScolling = true;
                $('html,body').animate({
                    scrollTop: 0
                }, 600, function() {
                    isScolling = false;
                    lastScrollTop = $(window).scrollTop();
                });
                console.log('Scroll up');
            }
            lastScrollTop = nowScrollTop;
        }
    });
});

最新更新