我想动画div的高度.这通常通过动画max-height属性在CSS中完成.
但是我需要在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;
}
});Run Code Online (Sandbox Code Playgroud)
#box {
margin-top: 20px;
border: 1px solid black;
background-color: #4f88ff;
width: 200px;
transition: max-height 0.25s linear;
overflow: hidden;
}Run Code Online (Sandbox Code Playgroud)
<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 …Run Code Online (Sandbox Code Playgroud)