2017-05-21 346 views
1

我有一個動態高度的div,我想在高度增長時使用動畫。問題是我無法設置div的高度(它必須是動態的),所以沒有什麼可以動畫的。元素動態高度的CSS高度動畫

.text { 
    transition: all .3s ease-in-out; 
    min-height: 20px; 
    max-height: 200px; 
    overflow: auto; 
} 

.max { 
    transition: all .3s ease-in-out; 
    height: 200px; 
    min-height: 200px; 
} 

https://jsfiddle.net/abk7yu34/5/

注意收縮動漫作品,因爲div有最小高度。

有沒有辦法在純CSS中解決這個問題?

+0

更改高度:200px至最大高度:200px; – Chiller

回答

2

刪除height: 200px;,所以你有兩個動畫擴展和崩潰。

此外,使用以下方法來對新行添加動畫:

@keyframes lineInserted { 
    from { 
    height: 0; 
    } 
    to { 
    height: 20px; /* your line height here */ 
    } 
} 
div[contenteditable] > div { 
    animation-duration: 0.3s; 
    animation-name: lineInserted; 
    transition: height 0.3s; 
} 

document.querySelector('#button').addEventListener('click', function() { 
 
    document.querySelector('.text').classList.toggle('max'); 
 
});
.text { 
 
    background: green; 
 
    color: #fff; 
 
    transition: all .3s ease-in-out; 
 
    min-height: 20px; 
 
    max-height: 200px; 
 
    overflow: auto; 
 
} 
 

 
.max { 
 
    transition: all .3s ease-in-out; 
 
    min-height: 200px; 
 
} 
 

 
@keyframes lineInserted { 
 
    from { 
 
    height: 0; 
 
    } 
 
    to { 
 
    height: 20px; /* your line height here */ 
 
    } 
 
} 
 
div[contenteditable] > div { 
 
    animation-duration: 0.3s; 
 
    animation-name: lineInserted; 
 
    transition: height 0.3s; 
 
}
<div class="text" contentEditable="true"></div> 
 
<button id="button">Click</button>

1

嘗試上的文字類去除最大高度屬性,並轉換到新的(動態)分高

.text { 
    background: green; 
    color: #fff; 
    transition: min-height .3s ease-in-out; 
    min-height: 20px; 
    overflow: auto; 
} 

.max { 
    transition: min-height .3s ease-in-out; 
    min-height: 200px; 
} 

https://jsfiddle.net/Alessi42/abk7yu34/8/

這是否會產生預期的效果?