gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:04:43 27 4
gpt4 key购买 nike

根据 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com