我已经使用以下动画一段时间了,它可以很好地展开/折叠元素:
const expanded = style({ height: '*', opacity: 1 });
const collapsed = style({ height: 0, opacity: 0 });
const animation = animate(`300ms cubic-bezier(0.4, 0.0, 0.2, 1)`);
export const expandCollapse = trigger('expandCollapse', [
transition(':enter', [collapsed, animation, expanded]),
transition(':leave', [animation, collapsed]),
]);
这对于通过
*ngIf
显示或隐藏元素时为其设置动画非常有用:
<div *ngIf="isExpanded" @expandCollapse>
<!-- Content Here -->
</div>
显然,我从未将其与使用
gap
的内容一起使用,因为当我在开始和结束时执行动画“捕捉”时。我以为我可以通过动画 gap
属性来解决这个问题,但没有运气:
const expanded = style({ height: '*', gap: '*', opacity: 1 });
const collapsed = style({ height: 0, gap: 0, opacity: 0 });
我怎样才能解决这个问题?
这是演示当前行为的 StackBlitz。
您面临的问题是因为 CSS 网格或 Flex 间隙更改无法使用基本 CSS 或 Angular 动画自动设置动画。许多浏览器不直接支持间隙属性来实现平滑事务,从而导致捕捉效果。
要解决此问题,您可以使用一种解决方法,即使用完全可动画化的 margin 或 padding 属性显式对间隙进行动画处理。
让我给你更新的代码。
修改样式:
const expanded = style({ height: '*', opacity: 1, marginTop: '*', marginBottom: '*' });
const collapsed = style({ height: 0, opacity: 0, marginTop: 0, marginBottom: 0 });
const animation = animate(`300ms cubic-bezier(0.4, 0.0, 0.2, 1)`);
export const expandCollapse = trigger('expandCollapse', [
transition(':enter', [collapsed, animation, expanded]),
transition(':leave', [animation, collapsed]),
]);
更新 HTML:
<div *ngIf="isExpanded" @expandCollapse>
<div class="content-wrapper">
<!-- Content Here -->
</div>
</div>
添加CSS(可选)
.content-wrapper {
display: flex; /* or grid, if needed */
/* other styling */
}