【发布时间】:2022-01-05 15:41:33
【问题描述】:
我有动态生成的按钮。单击任何一个按钮时,我希望根据激活的按钮来更改按钮的 css。
我的代码:
HTML:
<div class="container">
<div class="scroll" scrollX="true">
<span *ngFor="let item of buttons; let i = index" (click)="genreSelect(item)"
><ion-button shape="round" [ngClass]="{activated: buttonActive}">{{item.catName}}</ion-button></span
>
</div>
TS:
this.buttons = [{
id: 1,
catName:'Electronics'
},{
id: 2,
catName:'Books'
},{
id: 3,
catName:'Furniture'
},{
id: 4,
catName:'Laptops'
}];
genreSelect(item){
console.log(item);
this.buttonActive = true;
}
CSS:
.activated:active{
background-color: red;
}
CSS 闪烁一秒钟然后消失。
如果按钮被激活,我怎样才能使 CSS 在那里。
【问题讨论】:
-
:active伪类仅在按下按钮时应用。如果您希望所有按钮状态的背景都为红色,您可以使用.activated, .activated:hover, .activated:active { background-color: red; }。 -
有了这个css,所有的按钮都被改变了。我只想更改所选按钮的 css
-
是的,您将所有按钮的
ngClass绑定到同一个变量 (buttonActive)。您需要多个变量。 -
由于您将按钮作为对象,您可以将键“活动”添加为布尔值,并通过单击事件将 bttn id 传递给方法,该方法将在所有 bttns 上将“活动”更改为 false,并将其设置为 true单击的 bttn,然后让按钮上的 ngClass 返回一个 css,以防 button.active 和另一个 css,如果!button.active
-
正如@MishaMashina 所说,要么在你的 JSON 对象中取一个布尔值,要么你可以使用索引作为选定按钮来添加你的 css。
标签: css angular ionic-framework