2015-06-09 29 views
1

應該如何管理CSS多行容器(例如內容塊或警報)展開動畫?多行容器展開動畫

http://plnkr.co/edit/Qq5fzeb3GBengviVNimC?p=preview

.alert { 
    background: turquoise; 
    color: white; 
    padding: 10px; 
    overflow: hidden; 

    opacity: 0; 
    max-height: 0; 
} 

body:hover .alert { 
    display: block !important; 
    opacity: 1; 
    -webkit-transition: 2s; 
    -moz-transition: 2s; 
    -ms-transition: 2s; 
    transition: 2s; 
    max-height: 100px; 
} 

這裏的問題是「多」,你可以看到,該塊的高度是不是一個固定值。

<div class="alert">Alert!<br>Alert!<br>Alert!</div> 

雖然max-height: 100px是接近真正的塊高度,它工作正常。如果max-height較小,則動畫最終會變得不穩定,並且max-height: 9999px會使轉換過快。

這樣做可以不計算JS中的確切高度嗎?

+0

據我所知,CSS高度不能順利過渡,而不固定大小。請參閱http://stackoverflow.com/questions/6089548/css3-height-transition-not-working進行討論。如果您使用JS,那麼您不必在CSS中提前指定高度,因爲該鏈接顯示,或者TijnvW在其答案中顯示。 – Palpatim

回答

-1

計算高度jQuery中進行實在的,我做了以下解決你的問題:

$("#out").html("Block height: " + $("#alert").height()); 
 
//solely for demonstration, you can delete this line 
 

 
$("#alert").css('height','0px'); 
 

 
$('#alert').mouseover(function(){ 
 
    $("#alert").css('height', '58px'); 
 
}); 
 
$('#alert').mouseout(function(){ 
 
    $("#alert").css('height', '0px'); 
 
});
#alert { 
 
    background: turquoise; 
 
    color: white; 
 
    padding: 10px; 
 
    overflow: hidden; 
 
    opacity: 0; 
 
    //max-height: 0; this causes .height() to always display '0' so delete this here, and set this via jQuery 
 

 
} 
 

 
body:hover #alert { 
 
\t display: block !important; 
 
\t opacity: 1; 
 
    -webkit-transition: 2s; 
 
    -moz-transition: 2s; 
 
    -ms-transition: 2s; 
 
    transition: 2s; 
 
// max-height: 100px !important; set this via jQuery 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<p>Hello!</p> 
 
<div id="alert">Alert!<br>Alert!<br>Alert!</div> 
 
<p>Hello again!</p> 
 

 
<span id="out"></span>

+0

在他們的問題中指定的OP:「這可以在沒有計算JS中的確切高度的情況下完成嗎?」 – Palpatim

+0

@Palpatim是的,這是第二個問題。如果不可能只用CSS,我會接受JS的回答。但是這樣的解決方案受到硬編碼高度的影響,高度也可以在縮放時改變,調整大小或改變塊內容。 – estus

+0

哎呀,完全忽略了'沒有'這個詞,對不起! 不知道這是否可以在純CSS中完成,所以我很好奇,如果任何人有其他解決方案 – SJDS