我想要使用 Angular 动画实现平滑的滑入和滑出动画。我正在使用 ngSwitch 来显示/隐藏这些组件。传入的组件会在前一个组件消失之前将其向上推。我尝试过添加延迟,但这并不能解决问题。
app.component.html
<div class="container" [ngSwitch]="counter">
<div @slideInOut *ngSwitchCase="1"></div>
<div @slideInOut *ngSwitchCase="2"></div>
<div @slideInOut *ngSwitchCase="3"></div>
<div @slideInOut *ngSwitchCase="4"></div>
</div>
<button (click)="handleNext()">Next</button>
app.component.scss
.container {
div {
width: 100px;
height: 100px;
background: pink;
}
}
app.component.ts
import { Component } from '@angular/core';
import { slideInOut } from './shared/animations';
@Component({
selector: 'my-app',
styleUrls: ['./app.component.scss'],
animations: [ slideInOut ],
templateUrl: './app.component.html',
})
export class AppComponent {
readonly name: string = 'Angular';
counter = 1;
boxArr = [1, 2, 3, 4]
handleNext(){
if(this.counter <= this.boxArr.length){
this.counter += 1
} else {
this.counter = 1
}
}
}
动画.ts
import { trigger, state, style, transition, animate, keyframes } from "@angular/animations";
export const slideInOut = trigger('slideInOut', [
transition(':enter', [
style({transform: 'translateX(100%)'}),
animate('200ms ease-in', style({transform: 'translateX(0%)'}))
]),
transition(':leave', [
animate('200ms ease-in', style({transform: 'translateX(-100%)'}))
])
])
最佳答案
问题在于:
1) 当您处理 display: block
时,无论是否还有剩余空间,元素都会占用整行宽度,因此您的幻灯片会分成两行
2) 如果我们通过添加 display: inline-block
来解决这个问题,我们就必须处理当有两个元素时它们比一个元素占用更多的空间。同时,translate
实际上并不移动您的元素,而只是移动它的可见部分(“物理”形状位于相同位置)
因此,通过幻灯片的绝对定位解决了这个问题
https://stackblitz.com/edit/angular-zciezz?file=src/app/app.component.scss
.container {
position: relative;
width: 100px;
height: 100px;
div {
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
background: pink;
}
}
关于javascript - :enter and :leave Angular animations 没有平滑过渡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58756640/