css - 在棱 Angular Material 中提升 md-card

标签 css angular angular-material2

根据 Material Design 规范:

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

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

我考虑过使用 (hover)= 和动画来做到这一点。我不太喜欢这种方法,我更希望它在悬停时提升。这样做的原因是,我在我的 UI 中使用卡片作为按钮。

最佳答案

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

该指令在用户的鼠标进入或离开元素时添加和删除高程类。

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 .

关于css - 在棱 Angular Material 中提升 md-card,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44593237/

相关文章:

php - 如何在单击 'Read More' 按钮时显示数据库的全部内容

javascript - 来自 Asp.Net Core 的 Angular 4 映射结果

angular - 包 '@angular/cli' 不是依赖项

css - 通过鼠标指针以 Angular 5 调整 div 的水平和垂直大小

angular - 如何在 Angular 2/4 Material 设计选择组件上添加图像

angular - 使用ajax调用获取数据后在MatTableDataSource中设置MatPaginator和MatSort

Angular Material matInput 内容右对齐

php - 无法在我的代码中使用 require 或 include 来包含我的 Css 文件

jquery - 为什么背景颜色不显示?

jquery - 在表单中上传文件