我想要动画化一个div的高度。通常情况下,可以通过动画化max-height
属性来实现。
然而,我需要在JS中实现这个效果。该div包含经常变化的动态内容,因此实际高度无法提前确定。
这是一个jsfiddle链接:https://jsfiddle.net/vpknxuk8/
var box = document.getElementById("box");
var button = document.getElementById("button");
var expanded = true;
button.addEventListener('click', function() {
if (expanded) {
box.style.maxHeight = 0;
expanded = false;
} else {
box.style.maxHeight = "";
expanded = true;
}
});
#box {
margin-top: 20px;
border: 1px solid black;
background-color: #4f88ff;
width: 200px;
transition: max-height 0.25s linear;
overflow: hidden;
}
<button id="button">Click</button>
<div id="box">
Hello World<br>
This is dynamic content<br>
The actual height won't be known ahead of time
</div>
盒子应该在高度为0和默认高度之间转换,但不知何故它没有动画效果。
其他关于此问题的StackOverflow版本仅涉及CSS-only解决方案或jQuery解决方案。