2012-04-29 42 views
1

我有一個內容div,另一個div位於第一個下面。第一個div的內容動態變化,其高度根據需要改變。通常,當第一個div的高度發生變化時,第二個div的位置會自動上下晃動。我如何動畫第二個div的運動,最好只使用CSS和JS(沒有jQuery)?其他內容大小更改時Animate div位置

這裏有一個視覺: enter image description here

左邊是我的兩個div,最初。有時,div1將在高度上展開以適應其內容,而div2將被壓低。我如何動畫div2的動作?

+0

只有CSS是非常困難的... –

+0

Dhaivat是對的。您希望頁腳在內容div的底部進行動畫製作,但不使用JS,則可能無法使用。 – DanRedux

+0

Dhaivat Pandya,DanRedux:OP至少要求CSS和JS –

回答

2
function init() { 
    var header = document.getElementById('header'); 
    var header_height = header.offsetHeight; 
    header.style.height = '10px'; 
    header.style.overflow = 'hidden'; 
    var i = 0; 
    var animation = setInterval(function() { 
     if (i <= header_height) { 
      header.style.height = (10 + i) + 'px'; 
     } else { 
      clearInterval(animation); 
      header.style.overflow = 'block'; 
     } 
     i++; 
    }, 10); 
} 

確定,需要或許有些票子嗎? 你必須移動究竟是不是「第二」分區,但「第一」,即通過移動會自動將底部的第二個(或結束第一的)希望這有助於

1

演示:http://jsfiddle.net/xS3y7/

#div1 { 
    width: 50px; // Parent div needs width and height for this to work. 
    height: 50px; 
    background-color : red; 
    position: relative; 
} 

#div2 { 
    position: absolute; //positioning based on parent. 
    width: 100%; // 100% width of parent 
    height: 20%; // 20% width of parent 
    background-color: blue; 
    bottom: 0px; // Place on the bottom 
}​ 

需要注意的重要一點是,家長<div>必須有絕對相對定位,孩子<div>必須有絕對的定位。絕對定位基於其最接近的父元素的位置(在這種情況下,爲#div1)。絕對定位使我們能夠將我們的元素放置在我們想要的任何位置(相對於父元素),計算關閉值,所以這非常強大。

對於一個很好的閱讀,請檢查克里斯科伊爾CSS-Tricks