我有两个 div( parent 和 child ),我想做一个基于自定义状态的特殊动画(关闭 => 打开 && 打开 => 关闭):
- 当状态从关闭 => 打开时:
我希望父 div 的不透明度从 0 变为 1,子 div 的不透明度从 比例从 0.3 到 1。 - 当状态从打开 => 关闭时:
我希望 css 属性返回到它们的原始值(父级的不透明度为 0,子级的比例为 (0.3))
好消息是当状态变为 => 关闭 => 打开时动画按预期工作(对于两个 div)。
坏消息是当状态从 open => close 时动画不工作(仅对子 div)。
说的够多了,这是我所做的:
View HTML:
<div [@openClose]="opened ? 'open' : 'close'" class="parent">
<div [@animateChild]="opened ? 'open' : 'close'" class="child">
<p>Child content</p>
</div>
</div>
在component.ts中:
@Component({
selector: 'app-my-component',
templateUrl: './my.component.html',
styleUrls: ['./my.component.css'],
animations: [
trigger('openClose', [
state('open', style({
opacity: 1,
visibility: 'visible',
})),
// when we go from close to open do these steps
transition('close => open', [
query(':self', [// animate div itself
animate('200ms ease-in', style({
opacity: 1,
visibility: 'visible',
}))
]),
query('@animateChild', animateChild())// then animate children (.child)
]),
transition('open => close', [
query(':self', animate('200ms ease-in')),
query('@animateChild', animateChild()),
]),
]),
trigger('animateChild', [
state('open', style({ opacity: 1, transform: 'scale(1)' })),
transition('close => open', [
animate('100ms ease-out')
]),
transition('open => close', [
style({ transform: 'scale(0.3)', opacity: 0 }),
animate('100ms ease-out')
])
])
]
})
export class MyComponent implements OnInit {
opened: boolean;
constructor() { }
ngOnInit() {}
open(){
this.opened = true;
}
close(){
this.opened = false;
}
}
在 CSS 文件中:
.parent{
width: 100%;
height: 100vh;
background: black;
opacity: 0;/* initialize opacity to 0 for the parent */
}
.child{
width: 50%;
background: white;
transform: scale(0.3);/* initialize scale to 0.3 for the child */
opacity: 0; /* and opacity to 0 to be invisible when component initialized */
}
这是 Stackblitz 上的例子:
https://stackblitz.com/edit/angular-bjuzyr
我这里做错了什么?
最佳答案
请你试试下面的动画代码:
animations: [
trigger('openClose', [
state('open', style({
opacity: 1,
visibility: 'visible',
})),
state('close', style({
opacity: 0,
visibility: 'visible',
})),
// when we go from close to open do these steps
transition('* => *', [
animate('200ms ease-in'),
]),
]),
trigger('animateChild', [
state('open', style({ opacity: 1, transform: 'scale(1)' })),
state('close', style({ opacity: 0, transform: 'scale(0.3)' })),
transition('* => *', [
animate('100ms ease-out')
])
])
]
关于html - Angular:自定义状态动画未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49585542/