在 angular material 中提升 md-card

Elevate md-card in angular material

根据 Material 设计规范:

On desktop, cards can have a resting elevation of 0dp and gain an elevation of 8dp on hover.

如何使用 Angular Material 2 创建此动画效果?

我考虑过使用 (hover)= 和动画来做到这一点。我不太喜欢这种方法,我更希望它在悬停时提升。为此,我在 UI.

中使用卡片作为按钮

要更改 md-card 的高度,请创建一个 class,如下所示:

.z-depth:hover {
    box-shadow: 0 8px 8px 8px rgba(0,0,0,.2), 0 8px 8px 0 rgba(0,0,0,.14), 0 8px 8px 0 rgba(0,0,0,.12) !important;
    transform: translate3d(0,0,0);
    transition: background .4s cubic-bezier(.25,.8,.25,1),box-shadow 280ms cubic-bezier(.4,0,.2,1);
}

您可以更改 box-shadow 数字以找到您要查找的确切海拔。

Plnkr demo.

对我来说,最好使用预定义的 css classes。并在用户将鼠标悬停在 md-card 上时切换此 class。要更改高度,请使用 mat-elevation-z{{elevationValue}}

A directive 是可重用和可配置的,可以应用于任意数量的元素。创建指令,并在模块的声明中引用它。

此指令在用户鼠标进入或离开元素时添加和删除高度 class。

import { Directive, ElementRef, HostListener, Input, Renderer2, OnChanges, SimpleChanges } from '@angular/core';

@Directive({
  selector: '[appMaterialElevation]'
})
export class MaterialElevationDirective implements OnChanges {

  @Input()
  defaultElevation = 2;

  @Input()
  raisedElevation = 8;

  constructor(
    private element: ElementRef,
    private renderer: Renderer2
  ) {
    this.setElevation(this.defaultElevation);
  }

  ngOnChanges(_changes: SimpleChanges) {
    this.setElevation(this.defaultElevation);
  }

  @HostListener('mouseenter')
  onMouseEnter() {
    this.setElevation(this.raisedElevation);
  }

  @HostListener('mouseleave')
  onMouseLeave() {
    this.setElevation(this.defaultElevation);
  }

  setElevation(amount: number) {
    const elevationPrefix = 'mat-elevation-z';
    // remove all elevation classes
    const classesToRemove = Array.from((<HTMLElement>this.element.nativeElement).classList)
      .filter(c => c.startsWith(elevationPrefix));
    classesToRemove.forEach((c) => {
      this.renderer.removeClass(this.element.nativeElement, c);
    });

    // add the given elevation class
    const newClass = `${elevationPrefix}${amount}`;
    this.renderer.addClass(this.element.nativeElement, newClass);
  }
}

然后可以将该指令应用于具有可选输入属性的元素。

<mat-card appMaterialElevation [defaultElevation]="variableHeight" raisedElevation="16">
    <mat-card-header>
        <mat-card-title>Card Title</mat-card-title>
    </mat-card-header>
    <mat-card-content>
        <p>
            This card changes elevation when you hover over it!
        </p>
    </mat-card-content>
</mat-card>

看到这个demo StackBlitz

另一种方法是在样式文件中获得 material 高度 类 并在那里使用它。例如在我的 scss 文件中我有:

@use '~@angular/material' as mat;

.my-card {
  // ...some-custom-styles
  &:hover {
    @include mat.elevation(12);
  }
}