我正在用打开/关闭动画在Elm中创建一个手风琴模块。最初,手风琴琴体具有属性style="height: 0"
。打开手风琴时,我会计算隐藏物体的高度,并通过更改属性style="height: <contentheight>"
来应用它。这就是我使CSS过渡正常工作的方式。
手风琴琴体完全展开后,我设置了style="height: auto"
。使用与CSS中的setTimeout
时间匹配的transition-duration
完成此操作。这样,如果打开后手风琴主体的内容发生变化,我就可以自动调整其大小。
为了在关闭手风琴时使CSS过渡正常工作,我首先将auto
替换为一个数值。我计算手风琴琴体的当前高度,并将其放入height
样式。 1毫秒后(使用setTimeout
),我更改为height: 0
。
此功能在Chrome浏览器中非常完美,但在IE 11和Edge中,它大约80%的时间失败。如果我将超时时间增加到50 ms,则每次都可以使用,但是当然会有明显的输入延迟。如果我使用Browser.Events.onAnimationFrame而不是1ms超时,则它可以在所有三种浏览器中使用,但是由于这需要Elm中的订阅,因此如果有更好的方法,那就更好了。
还有其他方法可以保证IE和Edge仅在1毫秒内检测到属性更改吗?
为什么不打开类并以这种方式进行更改时将其添加到手风琴?
在下面的示例中,在scaleY
属性上使用变换可以使您从零变到自动高度。
document.getElementById('accordion-button').addEventListener('click', () => {
document.getElementById('accordion').classList.toggle('expanded');
});
#accordion {
transform: scaleY(0);
transform-origin: top;
transition: transform 300ms ease; // or however you want to handle this
}
#accordion.expanded {
transform: scaleY(1);
}
<button id="accordion-button">Click me</button>
<ul id="accordion">
<li>Some content</li>
<li>Some more</li>
</ul>
这样,所有内容都将由CSS过渡处理。