2016-05-17 142 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>