【问题标题】:Apply CSS transition to element in Angular将 CSS 过渡应用于 Angular 中的元素
【发布时间】:2021-09-29 21:52:48
【问题描述】:

我在 Angular 12 应用程序上有以下弹出元素:

<div class="window" [hidden]="!active" (clickOutside)="close()">
  <ng-content select="[window]"></ng-content>
</div> 

是否可以应用 DIV 显示/隐藏的 CSS 过渡?

我正在考虑改变它的不透明度。

【问题讨论】:

    标签: css angular


    【解决方案1】:

    我认为您最好使用角度动画。它更灵活:

    这是我正在使用的一个:

    import { trigger, state, style, transition, group, animate } from '@angular/animations';
    
    export const FadeInOutAnimation =
      trigger('fadeInOut', [
        state('in', style({
          'opacity': '1',
        })),
        state('out', style({
          'opacity': '0',
        })),
        transition('in => out', [
          group([
            animate('600ms ease-in-out', style({
              'opacity': '0'
            })),
          ])
        ]),
        transition('out => in', [
          group([
            animate('600ms ease-in-out', style({
              'opacity': '1'
            })),
          ])
        ]),
      ]);
    

    并使用它:

    @Component({
      selector: 'app-popup',
      templateUrl: './popup.component.html',
      styleUrls: ['./popup.component.scss'],
      animations: [
        FadeInOutAnimation
      ]
    })
    export class PopupComponent implements OnInit {
    
      constructor() {
      }
    
      ngOnInit() {
      }
    
      @Input() dialogVisible: boolean;
    
    }
    
    <div class="popup-background" [@fadeInOut]="dialogVisible"></div>
    <div class="popup-content form-control-normal" [@fadeInOut]="dialogVisible">
      <ng-content></ng-content>
    </div>
    

    但我认为您仍然需要将 display: blockdisplay: none 添加到状态。

    【讨论】:

      【解决方案2】:

      在css中设置样式:

      .fade-out {
        visibility: hidden;
        opacity: 0;
        transition: visibility 0s linear 300ms, opacity 1000ms;
      }
      
      .fade-in {
        visibility: visible;
        opacity: 1;
        transition: visibility 0s linear 0s, opacity 1000ms;
      }
      

      并在弹出组件的 HTML 中应用该类:

      <div class="container" [class]="active ? 'fade-in' : 'fade-out'">
      

      查看此 Stackblitz:https://stackblitz.com/edit/angular-ivy-5whet6?file=src/app/popup/popup.component.html

      【讨论】:

        猜你喜欢
        • 2016-02-13
        • 2020-01-13
        • 2021-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-28
        • 2015-12-28
        • 2017-02-19
        相关资源
        最近更新 更多