jQuery scrollTop动画循环问题

时间:2014-02-25 17:56:37

标签: jquery html animation scrolltop

在使用jQuery时,我不是很精明,而且我正在开发一个项目,该项目涉及动画手机中的某个部分,以便向下滚动显示手机内的内容。我有2个手机,并排,有动画。它的工作方式是左边滚动,暂停,然后右边滚动,然后暂停。他们会这样做直到他们结束。它们还有一个可以用它动画的球形图标。

我得到了它的工作,但项目的范围是当用户滚动到页面上的该部分时,手机中的滚动动画将动画。当我试图让它工作时,动画循环回到顶部,我不希望他们这样做。我不知道是什么导致了这个问题。

如果有人能提供任何帮助,我将非常感激。我提前为我写得不好的jQuery道歉。如果有更好的方法来编写动画,我肯定会修改它。

这是最适合我的jQuery:

http://jsfiddle.net/qxwKL/

$(function(){
    $(".portrait .mobile-container").animate({ scrollTop: 560 }, 1200).delay(3000).animate({ scrollTop: 1200 }, 1200);  
    $(".portrait .ball").animate({ top: 720 }, 1200, "linear").delay(3000).animate({ top: 1280 }, 1200, "linear");  

    $(".landscape .mobile-container").delay(2000).animate({ scrollTop: 900 }, 1500).delay(3000).animate({ scrollTop: 1300 }, 1500);  
    $(".landscape .ball").delay(2000).animate({ top: 1000 }, 1300, "linear").delay(3000).animate({ top: 1300 }, 1300, "linear");   
}); 

这是我遇到的问题。您需要滚动到带有电话的部分才能启动动画:

http://jsfiddle.net/Gsk4n/3/

$(window).scroll(function() {
    $('.mobile-device').each(function(){
        var imagePos = $(this).offset().top;
        var topOfWindow = $(window).scrollTop();

        if (imagePos < topOfWindow+900) {
            $('.portrait-contain', this).delay(1000).animate({ scrollTop: 560 }, 1000).delay(3000).animate({ scrollTop: 1590 }, 1000);
            $('.portrait-contain .ball', this).delay(1000).animate({ top: 720 }, 1000, "linear").delay(3000).animate({ top: 1700 }, 1000, "linear");                    

            $('.landscape-contain', this).delay(3000).animate({ scrollTop: 590 }, 1000).delay(3000).animate({ scrollTop: 1200 }, 1000);
            $('.landscape-contain .ball', this).delay(3000).animate({ top: 650 }, 1000, "linear");
        }
    });
});

1 个答案:

答案 0 :(得分:0)

我的名字是Saucier(:这是你的一个段落

但至于你的问题,我能够用一些技巧来弥补这种情况。第一个是我在imagePos <= topOfWindow之前没有启动动画,这意味着手机的内容部分必须完全可见。如果你想更改它以便更快地发生,请从imagePos

中减去

我改变的第二件事是你的主要问题所在。在达到该点后,任何时候滚动窗口时,您的动画都会被触发。为了解决这个问题,我添加了一个名为hasAnimated的布尔值来跟踪动画事件是否已经触发,并将所有动画放在依赖于该布尔值的if语句中。

if(!hasAnimated) {
    ... All of your animations ...
}

我添加的下一件事是

if($(this) == $('.mobile-device:last')) {
    hasAnimated = true;
}

这会让您的动画不会多次触发(一旦应用了最后一个元素的动画,则为if)

我还添加了一个

else {
    hasAnimated = false;
}
如果用户向上滚动,则在主if语句之后

重置动画。如果您不想要此功能并希望动画只运行一次,请删除此

最后,我添加了一个

.stop(true,true)
.animate({ scrollTop: 100 }, 1000) //  I used `scrollTop: 0` for the containers

对于每个动画序列,以便在再次运行动画之前重置动画。当用户在动画点上方滚动时,您可能希望更改此操作,我只是将其放在此处以便于编码以显示您可以

Here's a demo所有这些(: