2013-10-05 127 views
0

我正在使用javascript滚动。我有以下的HTML代码javascript窗口滚动问题

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

回答

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

});

+0

它不工作,他们我想要的。目前,当我滚动一次后,它将div标签更改为蓝色标签,然后回到红色。 – 2619

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动画到顶端:0,它没有动画过去的动画。