天天看點

fullpage.js如何重置每頁的animate()動畫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==){
        $("#exp-1").animate({top:"5%",opacity:"1"},,function(){
            $("#exp-2").animate({bottom:"0",opacity:"1"},,function(){
                $("#exp-3").animate({bottom:"0",opacity:"1"},,function(){
                    $("#exp-4").animate({bottom:"0",opacity:"1"},)
                });
            })
        })
    }
}
           

比如上面的代碼,當加載完第二頁的動畫後,再翻到第二頁就不會在出現動畫,因為CSS值已經達到目标值。

如此一來我們想要重複載入動畫的話必須先重置CSS屬性。如下代碼:

afterLoad: function(anchorLink, index){
    if(index==){
        $("#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"},,function(){
            $("#exp-2").animate({bottom:"0",opacity:"1"},,function(){
                $("#exp-3").animate({bottom:"0",opacity:"1"},,function(){
                    $("#exp-4").animate({bottom:"0",opacity:"1"},)
                });
            })
        })
    }
}
           

但是這樣一來翻到第二頁會将CSS重置的過程暴露給使用者,使用者體驗較差,我們可以選擇用onLeave來重置CSS:

onLeave: function(index,nextIndex,direction){
    if(nextIndex==){
        $("#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"},,function(){
            $("#exp-2").animate({bottom:"0",opacity:"1"},,function(){
                $("#exp-3").animate({bottom:"0",opacity:"1"},,function(){
                    $("#exp-4").animate({bottom:"0",opacity:"1"},)
                });
            })
        })
    }
}
           

這樣一來animate()動畫便可以重複播放。

但另一個問題卻暴露出來:頁面間快速來復原動時,未執行完的動畫會在滾動回該頁面時繼續執行。這樣也會帶來不好的使用者體驗。我們可以用jQuery的stop()方法。

onLeave: function(index,nextIndex,direction){
    if(nextIndex==){
        $("#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"},,function(){
            $("#exp-2").stop(true,true).animate({bottom:"0",opacity:"1"},,function(){
                $("#exp-3").stop(true,true).animate({bottom:"0",opacity:"1"},,function(){
                    $("#exp-4").stop(true,true).animate({bottom:"0",opacity:"1"},)
                });
            })
        })
    }
}
           

這樣便大功告成了。