我試圖在文本更改時過渡高度更改。元素文本更改時的過渡高度
我目前正在過渡CSS max-height
屬性,因爲它比height
更靈活。
我的策略是:
- 文字將被包裹在一個
<span>#text</span>
和放置在主容器內。 - 然後進行跨度
display: inline-block
, - 然後設置主/包裝元素的
max-height
的跨度clientHeight
。
這幾乎奏效,問題在於它只有在前一個高度小於新高度時纔會轉換,也就是說,它只是從小到大,而不是從大到小轉變。
以下代碼。
var contents = [
"a".repeat(10),
"Bb".repeat(30),
"Cc".repeat(40),
"D".repeat(15),
"Ee".repeat(20),
"Ff".repeat(60),
"g".repeat(25)
]
changeText.addEventListener('click', function() {
text.textContent = randomText();
wrapper.style.maxHeight = text.clientHeight + 'px';
});
function randomText() {
return contents[ Math.floor(Math.random() * contents.length) ];
}
#wrapper {
background-color: #ccc;
padding: 5px 10px;
word-break: break-all;
width: 200px;
overflow: hidden;
/* set to the minimum height the #wrapper can be */
max-height: 18px;
transition: max-height 0.3s;
}
#wrapper > span {
display: inline-block;
}
<button id="changeText">change text</button>
<div id="wrapper">
<span id="text">no change</span>
</div>
確定嗎?因爲它並不是從大到小,而只是它從大到小而不是平滑過渡 –
哦,我明白你的意思了,沒有真正理解這個問題 –