fullpage.js如何重置每頁的animate()動畫
阿新 • • 發佈:2018-11-04
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)
});
})
})
}
}
這樣便大功告成了。