我有3张席子卡,当鼠标与它们互动时,它们会升高。
目的是将过剩状态保持在所选垫板上(通过click()
pqyhitler 回答:如何使用物料提升指令在选定的垫板上保持悬停状态
您可以尝试添加具有与元素悬停时相同的属性的类,然后通过click事件将该类添加/删除到元素中
CSS
div.target:hover,.mouseclick{
"properties"
}
JS
document.querySelector("div.target").onclick =
function(this){
if(this.classList.indexof("mouseclick") == -1){
this.classList.add(".mouseclick");
}else{
this.classList.remove(".mouseclick")
}
}
,
我会使用ngClass。您可以将变量绑定到CSS类,然后基于该变量切换它。
它看起来像这样:
.html
<mat-card [ngClass]="{'text-success':clicked === 'card1'}" appMaterialElevation (click)="select(titles[0])">
<mat-card-header>
<mat-card-title>{{titles[0]}}</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>
.ts
@Component{...}
clicked: string = '';
select(clickedVar: string) {
this.clicked = card1
}
根据需要重复制作卡片。只需为您想要的样式定义一个CSS类即可。
在此处查看更多信息:https://codecraft.tv/courses/angular/built-in-directives/ngstyle-and-ngclass/
,嗨,我已经重构了您的代码,可以在这里找到堆栈
https://stackblitz.com/edit/angular-material-elevation-hover-kpypah
首先,您必须创建带有isSelected属性的类标题,该属性在选择项目时会更改。
如果我重构他的HTML以使用NgFor 最后我添加了一个CSS类来管理悬停事件
import { Component,OnInit } from '@angular/core';
@Component({
selector: 'my-app',templateUrl: './app.component.html',styleUrls: [ './app.component.css' ]
})
export class AppComponent {
defaultElevation = 2;
raisedElevation = 8;
titles:title[] = [{name:'title1'},{name:'title2'},{name:'title3'}];
titleSelected;
name = 'Angular';
select(title) {
// clear all selection
this.titles.map(t=>t.isSelected = false);
// select the current item
title.isSelected = true;
this.titleSelected = title;
}
}
export class title {
name: string;
isSelected?: boolean;
}
mat-card:hover {
box-shadow: 0 5px 5px -3px rgba(0,.2),0 8px 10px 1px rgba(0,.14),0 3px 14px 2px rgba(0,.12);
}
<p>Title selected : {{ titleSelected?.name }}</p>
<ng-container *ngFor="let item of titles">
<mat-card (click)="select(item)"
[class.mat-elevation-z2]="!item.isSelected"
[class.mat-elevation-z8]="item.isSelected">
<mat-card-header>
<mat-card-title>{{item.name}}</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><br>
</ng-container>