2012-01-25 41 views
0

我有一个标题。在该标题下方,我有一个包含2个div并排放置的包装。我想让正确的div在它所属的包装(#wrapper)在页面顶部开始“消失”时呈现动画效果。我尝试了$(window).scroll,但问题是,即使包装并未开始在顶部消失,动画也会启动。我希望我明确解释我的问题。预先感谢您的回复。干杯。马克。Jquery动画div当它的包装开始“消失”在顶部

我的HTML:

<div id="header"></div> 
    <div id="wrapper"> 
     <div id="contentWrapper"> 
      <div id="contentOne" class="content">This is contentOne</div> 
      <div id="contentTwo" class="content">This is contentTwo</div> 
      <div id="contentThree" class="content">This is contentThree</div> 
      <div id="contentFour" class="content">This is contentFour</div> 
     </div> 
    </div> 

我的CSS:

#header{ 
    width:960px; 
    height:300px; 
    background-color:rgba(1,1,1,0.3); 
    margin:5px auto;} 

#wrapper{ 
    width:960px; 
    height:auto; 
    margin:0 auto; 
    background-color:rgba(238,221,130,0.6); 
    border:5px solid purple; 
    overflow:hidden;} 

#contentWrapper{ 
    width:1910px; 
    height:auto; 
    background-color:rgba(70,130,180,0.4); 
    float:left; 
    position:relative;} 

.content{ 
    width:465px; 
    height:auto; 
    margin:10px 0 10px 10px; 
    padding:0; 
    background-color:rgba(205,92,92,0.4); 
    float:left;} 

#contentOne{ 
    height:2000px;} 

我的JS:

$(window).scroll(function() { 
    $("#contentTwo").stop().animate({ 
     "marginTop": ($(window).scrollTop() + 10) + "px" 
    }, "fast"); 
}); 
+0

滚动卷轴上的事件触发,所以每当你卷轴1或两个像素,它会开始移动。它什么都不知道。 –

回答

1

你必须占包装的位置以及上滚动窗户。

http://jsfiddle.net/eqXMC/

使用示例代码修改JS:

$(window).scroll(function() { 

    var newMarginTop = Math.max(0, $(window).scrollTop() - $('#contentWrapper').offset().top) + 10; 

    $("#contentTwo").stop().animate({ 
     "marginTop": newMarginTop + "px" 
    }, "fast"); 
}); 
+0

你好罗斯。你摇滚!这正是我想要的。非常感谢。 – Marc

+0

高兴地帮助:) –