2013-06-21 139 views
0

我想對像車庫門這樣的div做一個javascript效果。 基本上我會在後面有一個div,前面有另一個div,它會從窗口滾動的底部到頂部收縮。jquery帶有窗口滾動的動畫

我有一個JSFiddle,只做我想做的事情,但我必須自己給出div大小,我希望大小根據窗口大小的滾動進行動態調整。

這裏的jsfiddle:http://jsfiddle.net/onlymushu/gTsHf/ 和代碼:

HTML 
<div id="container"> 
    <div id="contents"> 
     1. This is going to be very big line. 
     2. This is going to be very big line. 
     3. This is going to be very big line. 
     4. This is going to be very big line. 
     5. This is going to be very big line. 
     6. This is going to be very big line. 
     7. This is going to be very big line. 
     8. This is going to be very big line. 
    </div> 
</div> 
<button id="up">up</div> 
    <button id="down">down</div> 

CSS 
body{ 
    height: 1500px; 
} 
#container{ 
    margin: 0 auto; 
    width:400px; 
    height:300px; 
    background-color: red; 
    Position:relative;border:1px #000 solid; 
} 
#contents{ 
    width:400px; 
    height:300px; 
    position:absolute; 
    background-color: white; 
    overflow:hidden; 
} 

JS 
$(document).ready(function(){ 
    $("#up").click(function(){ 
     $("#contents").animate({height:"0px"},500); 
    }); 
    $("#down").click(function(){ 
     $("#contents").animate({height:"300px"},500); 
    }); 
}); 

謝謝你這麼多

回答

0

如果您在#container的設置

position:fixed; 

會坐以待斃,而滾動條移動。 然後在你的文件準備功能,確保有足夠的空間用於滾動:

var minHeight = $("#container").height() * 4; 
if ($("body").height() < minHeight) $("body").height(minHeight); 

而在滾動功能,使用滾動的百分比:

$(window).scroll(function() { 
    var newSize = $("#container").height() * (1 - $(window).scrollTop()/($(document).height() - $(window).height())); 
    $("#contents").css('height',newSize); 
}); 

我會建議在沒有動畫滾動功能,因爲它會被頻繁地調用。

我把更新your fiddle

+0

我看着它在我的手機其似乎fairely簡單的自由。非常感謝,我今晚會在電腦上查看它。我會記住你的建議。 – onlymushu