fullpage.js如何重置每页的animate()动画

fullpage.js如何重置每页的animate()动画


使用fullpage.js和jQuery animate()动画的朋友一定会有这样的问题,页面来回滚动时,动画只能执行一遍。
一种解决方法是改用CSS3执行动画,把CSS绑定在section.active上。
但是毕竟CSS3没有jQuery的兼容性好,如果我们需要用到animate()该怎么办呢?
jQuery的animate()更像是CSS3的transition+transform,而不是像animation,animate()是会改变dom样式的

afterLoad: function(anchorLink, index){
    if(index==2){
        $("#exp-1").animate({top:"5%",opacity:"1"},700,function(){
            $("#exp-2").animate({bottom:"0",opacity:"1"},700,function(){
                $("#exp-3").animate({bottom:"0",opacity:"1"},700,function(){
                    $("#exp-4").animate({bottom:"0",opacity:"1"},700)
                });
            })
        })
    }
}

比如上面的代码,当加载完第二页的动画后,再翻到第二页就不会在出现动画,因为CSS值已经达到目标值。
如此一来我们想要重复载入动画的话必须先重置CSS属性。如下代码:

afterLoad: function(anchorLink, index){
    if(index==2){
        $("#exp-1").css({bottom:"-20%",opacity:"0"});
        $("#exp-2").css({bottom:"-20%",opacity:"0"});
        $("#exp-3").css({bottom:"-20%",opacity:"0"});
        $("#exp-4").css({bottom:"-20%",opacity:"0"});
        $("#exp-1").animate({bottom:"0",opacity:"1"},700,function(){
            $("#exp-2").animate({bottom:"0",opacity:"1"},700,function(){
                $("#exp-3").animate({bottom:"0",opacity:"1"},700,function(){
                    $("#exp-4").animate({bottom:"0",opacity:"1"},700)
                });
            })
        })
    }
}

但是这样一来翻到第二页会将CSS重置的过程暴露给用户,用户体验较差,我们可以选择用onLeave来重置CSS:

onLeave: function(index,nextIndex,direction){
    if(nextIndex==2){
        $("#exp-1").css({bottom:"-20%",opacity:"0"});
        $("#exp-2").css({bottom:"-20%",opacity:"0"});
        $("#exp-3").css({bottom:"-20%",opacity:"0"});
        $("#exp-4").css({bottom:"-20%",opacity:"0"});
        $("#exp-1").animate({bottom:"0",opacity:"1"},700,function(){
            $("#exp-2").animate({bottom:"0",opacity:"1"},700,function(){
                $("#exp-3").animate({bottom:"0",opacity:"1"},700,function(){
                    $("#exp-4").animate({bottom:"0",opacity:"1"},700)
                });
            })
        })
    }
}

这样一来animate()动画便可以重复播放。
但另一个问题却暴露出来:页面间快速来回滚动时,未执行完的动画会在滚动回该页面时继续执行。这样也会带来不好的用户体验。我们可以用jQuery的stop()方法。

onLeave: function(index,nextIndex,direction){
    if(nextIndex==2){
        $("#exp-1").css({bottom:"-20%",opacity:"0"});
        $("#exp-2").css({bottom:"-20%",opacity:"0"});
        $("#exp-3").css({bottom:"-20%",opacity:"0"});
        $("#exp-4").css({bottom:"-20%",opacity:"0"});
        $("#exp-1").stop(true,true).animate({bottom:"0",opacity:"1"},700,function(){
            $("#exp-2").stop(true,true).animate({bottom:"0",opacity:"1"},700,function(){
                $("#exp-3").stop(true,true).animate({bottom:"0",opacity:"1"},700,function(){
                    $("#exp-4").stop(true,true).animate({bottom:"0",opacity:"1"},700)
                });
            })
        })
    }
}

这样便大功告成了。

猜你喜欢

转载自blog.csdn.net/shengandshu/article/details/56012642