2016-05-17 143 views
1

嗨,我需要動畫元素取決於滾動。我的觀點是設置元素的頂部位置1200像素,但是開始製作動畫上1000像素,並完成它時,它通過1800px但它啓動動畫上1400px,完成誰知道滾動位置上的jquery動畫

HTML

<div class="container"> 
    <section id="first-section"></section> 
    <section id="second-section"></section> 
</div> 

CSS

#second-section { 
    position: relative; 
    top: 1200px; 
    left: 0; 
    height: 200px; 
    border: 2px solid blue; 
    width: 100%; 
    background-color: red; 
    opacity: 1; 
} 

JAVASCRIPT

$(window).scroll(function() { 
    var top = $(this).scrollTop(); 
    if (top > 1000 && top < 1800) { 
     $("#second-section").stop().animate({ 
      opacity: "1" 
     }, 'slow'); 
    } else { 

     $("#second-section").stop().animate({ 
      opacity: "0" 
     }, 'slow'); 
    } 
}); 
+0

你有沒有聽說過[skrollr(http://prinzhorn.github.io/skrollr/)。您可以根據滾動位置輕鬆製作元素。 – Hareesh

+0

不,我沒有..但是,謝謝我要去嘗試它:) – george

回答

0

您的狀況不正確。爲此,您需要獲得元素的heightposition

見我的例子

$(window).scroll(function() { 
 
    var winHeight = $(this).height(); 
 
    var scrollTop = $(this).scrollTop(); 
 
    
 
    var elemHeight = $("#first-section").height(); 
 
    var elementTop = $("#first-section").position().top; 
 
     
 
    if (elementTop < scrollTop + winHeight && scrollTop < elementTop + elemHeight) 
 
     var opacity = 1; 
 
    else 
 
     var opacity = 0; 
 
    
 
    $("#first-section").stop().animate({ 
 
     opacity: opacity 
 
    }, "slow"); 
 
});
.container { 
 
    height: 2000px; 
 
} 
 

 
#first-section { 
 
    position: relative; 
 
    top: 1200px; 
 
    left: 0; 
 
    height: 200px; 
 
    border: 2px solid blue; 
 
    width: 100%; 
 
    background-color: red; 
 
    opacity: 0; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="container"> 
 
    <section id="first-section"></section> 
 
</div>