0

我正在研究javascript滚动。我有以下html代码

JSFIDDLE

<div class="wrapper">
    <div class="red div current"></div>
    <div class="blue div"></div>
    <div class="green div"></div>
    <div class="yellow div"></div>
</div>

在上面的代码中,我有四个 div 标签red, blue, green and yellow。它们都在以下css中。

html, body {
    height: 100%;
}
.wrapper {
    overflow: hidden;
    height: 100%;
}
.div {
    position: relative;
    height: 100%;
}
.red {
    background: red;
}
.blue {
    background: blue;
}
.green {
    background: green;
}
.yellow {
    background: yellow;
}

在上面的 html 和 css 中,红色的 div 标签是当前标签,这意味着用户正在屏幕上看到红色的 div 标签。现在我要做的是,当用户滚动一次窗口时,下一个 div 标签(即蓝色)将被动画化并移动到顶部,并且对用户可见,而红色 div 标签将位于蓝色标签的后面。同样的过程也适用于绿色和黄色。

问题是,当用户滚动一次时,div 标签应该设置动画,但是我当前的 javascript 代码一直在读取滚动并一个接一个地为 div 标签设置动画。我想要的是当用户滚动一次然后滚动应该被禁用,直到蓝色 div 标签被动画。然后应该启用滚动。同样,当用户第二次滚动时,滚动应该禁用,直到绿色 div 标签完成其动画。黄色也一样。

我怎样才能达到上述目标?

这是我的 javascript

$(window).on("scroll", function () {
    var next = $('.current').next();
    var height = next.outerHeight();

    next.animate({top: '-=' + height}, 500, function () {
        $(this).prev().removeClass('current');
        $(this).addClass('current');
    });
});
4

2 回答 2

0

请查看更新JsFiddle

$(window).on("scroll", function () {
var next = $('.current').next();
var height = $('.current').outerHeight();
$('.current').prevAll().each(function(){
    height += $(this).outerHeight();
});

next.animate({top: '-=' + height}, 500, function () {
    $(this).prev().css('top','');
    $(this).prev().toggleClass('current');
    $(this).toggleClass('current');
});

});

于 2013-10-05T06:05:50.227 回答
0

您的示例未按预期工作的主要原因是您相对定位了 div,并且没有将它们移动到正确的位置。

工作JSFiddle:

http://jsfiddle.net/seanjohnson08/rVVuc/6/

.wrapper {
    overflow: hidden;
    height: 100%;
    position: relative;
}
.div {
    position: absolute;
    height: 100%;
    width: 100%;
    top: 100%;
}
.current{
    top: 0;
}

如果您正在寻找一种方法来限制触发的滚动事件的数量,请尝试限制:http ://benalman.com/projects/jquery-throttle-debounce-plugin/ 。我的解决方案不需要这个,因为无论它触发滚动事件多少次,它只会告诉 jquery 动画到 top:0,它不可能动画过去。

于 2013-10-05T08:07:42.260 回答