[英]transition height when element text change
当文本更改时,我正在尝试转换高度的更改。
我目前正在过渡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>
编辑:我认为max-height不能单独工作的原因是span元素的高度将包装器的高度更改为小于先前的max-height,因此浏览器在不利用max height的情况下设置了高度。 由于不使用max-height来设置高度,因此没有过渡。
-
如何同时设置高度和最大高度的动画?
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.height = text.clientHeight + 'px'
wrapper.style.maxHeight = text.clientHeight + 'px'
});
function randomText() {
return contents[ Math.floor(Math.random() * contents.length) ];
}
并更新css以转换高度:
#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: all 0.3s;
}
#wrapper > span {
display: inline-block;
}
工作演示: https : //jsfiddle.net/2p5zjtud/1/
CSS编辑:
#wrapper {
background-color: #ccc;
padding: 5px 10px;
word-break: break-all;
width: 200px;
overflow: hidden;
/* set to the minimum height the #wrapper can be */
transition: height 1s;
}
#wrapper > span {
min-height: 1em;
display: inline-block;
}
JS编辑:
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.height = text.clientHeight + 'px';
});
function randomText() {
return contents[ Math.floor(Math.random() * contents.length) ];
}
好吧,我使用的是代码片段,它从大到小,从小到大,您唯一的问题就是我所看到的宽度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.