2013-06-22 65 views
0

我想要一類已被應用後,動畫元素的高度,這裏的簡化代碼:CSS3動畫無法按預期工作

HTML

<div class="section"> 
    <div class="panel"> 
    <a href="#" class="toggle">Click</a> 
    <div class="panel-content"> 
     Some content... 
    </div> 
    </div> 
</div> 

CSS

.section { 
    position: relative; 
    width: 500px; 
    height: 200px; 
    margin: 100px auto; 
    background: #ccc; 
} 

.panel { 
    width: 65%; 
    position: absolute; 
    left: 0; 
    bottom: 0; 
} 

.toggle { 
    display: inline-block; 
    height: 15px; 
    background: #ddd; 
} 

.panel-content { 
    max-height: 0; 
    overflow: hidden; 
    transition: max-height 1s; 
} 

.active .panel-content { 
    max-height: 9999px; 
} 

JS

​​

當我點擊.toggle鏈接active.panel元素設置爲.panel-content高度的動畫,但是當第一次添加類時,內容顯示沒有動畫,當它被刪除時,元素需要一秒(轉換的持續時間)到開始動畫。你可以看到現場演示在這裏:http://codepen.io/javiervd/pen/bLhBa

我試圖與位置和溢流性能,以及玩,但我不能讓它工作,也許有達到同樣的效果另一種方式?

在此先感謝。

回答

1

發生什麼事情時,您需要執行transition。這是不是你想要的,但讓我告訴你一件事:

.pannel-content{ 
    height:0; 
} 
.pannel-content:hover{ 
    height:50px; transition:height 2s; 
} 

這是怎麼transition作品。你還沒有創建一個動作。沒有點擊僞類,並且你不想影響相同的元素。嘗試使用jQuery,如。

<html> 
    <head> 
    <style type='text/css'> 
     .active .pannel-content{ 
     display:none; height:9999px; 
     } 
    </style> 
    </head> 
<body> 
    <div class='section'> 
    <div class='panel'> 
     <a href='#' class='toggle'>Click</a> 
     <div class='panel-content'> 
     Some content... 
     </div> 
    </div> 
    </div> 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> 
    <script type='text/javascript'> 
    $('.toggle').click(function(){ 
     $('.active .pannel-content').show('slow'); 
    }); 
    </script> 
</body> 
</html> 

你也可以使用jQuery的.animate()方法。當然,我會建議您使用申報DOCTYPE並使用<meta>標籤。你也應該使用外部CSS,因爲它會緩存在你的用戶瀏覽器內存中。
有關詳細信息,請訪問http://api.jquery.com/show/和。

+0

此。完美的答案。 –

+0

我做的活動類添加到我的'.panel'元素,使過渡發生,我只是ommitted爲簡潔,但它在我張貼,我雖然更新我使用JavaScript答案codepen。 – javiervd