2017-06-05 113 views
0

我有一個網站,當你滾動,它「順利」(在jQuery中的動畫滾動頂部)到另一個部分,否認你滾動到另一個網站。現在,我想要做的是,當您滾動到第2部分時,元素會顯示一些動畫,當您離開它時,它會消失,等等......當滾動不工作的動畫 - jQuery

我這樣做了,但它只適用於刷新該頁面和我已經在該部分。在其他情況下,它不起作用。我認爲它不起作用,因爲當你調用$(window).scrollTop()時,它立即返回scrollTop,但它實際上應該等待750ms讓滾動動畫完成。我試圖使用setTimeOut和其他東西,但我不能讓它運行。

下面是代碼:

function animacionObjetosDeSections() { 
$(window).scroll(function() { 
    //each height of the sections 
    var altoSection2 = $('#section2').offset().top; 
    var altoSection3 = $('#section3').offset().top; 

    //if scrolltop is the same to the height of section2, it displays the animation, else it returns to original state 
    if ($(window).scrollTop() == altoSection2) { 
     $('.view-of-page').animate({left: '2%'},600); 
     $('.page-info h2').animate({opacity: 1}, 650); 
    } else { 
     $('.view-of-page').animate({left: '-50%'},600); 
     $('.page-info h2').animate({opacity: 0}, 650); 
    } 
}); 

}

編輯:

知道它的工作原理,但每個滾動它承認像30個滾動事件,我必須等待那些30個事件* 750ms使功能再次工作。

CODE:

function animacionObjetosDeSections() { 
$(window).scroll(function() { 
    setTimeout(function() { 
    //each height of the sections 
    var altoSection2 = $('#section2').offset().top; 
    var altoSection3 = $('#section3').offset().top; 

    //if scrolltop is the same to the height of section2, it displays the animation, else it returns to original state 
    if ($(window).scrollTop() == altoSection2) { 
     alert("hola"); 
     $('#section2 .view-of-page').animate({left: '2%'},600); 
     $('#section2 .page-info h2').animate({opacity: 1}, 650); 
    } else { 
     $('#section2 .view-of-page').animate({left: '-50%'},600); 
     $('#section2 .page-info h2').animate({opacity: 0}, 650); 
    } 
     },701); 
}); 

}

回答

0

使用slideup()slidedown()功能,當你到達的那款。 例如,當您滾動到第2部分時,使用slidedown()函數在您的部分div上,它將與動畫一起出現,當您離開該部分時,請使用slideup()函數,並且您的部分將隨動畫消失。

+0

但我想水平滑動而不是垂直滑動。我認爲它不會工作,因爲延遲它得到scrollTop()的時間相同的問題 –