我有两个div(父级和子级),我想根据自定义状态(关闭=>打开&&打开=>关闭)制作特殊的动画:


当状态从关闭=>打开时:我希望父div的不透明度从0变为1,而孩子的
从0.3扩展到1。
当状态从打开=>关闭时:我希望css属性返回其原始值(父级不透明度0,子级scale(0.3))


好消息是,当状态为=>关闭=>打开时,动画将按预期方式工作(两个div)。

坏消息是,当状态从打开=>关闭时,动画不起作用(仅适用于子div)。

聊够了,这就是我所做的:

视图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')
   ])
])
]

07-26 09:36
查看更多