【问题标题】:Add CSS based on Button Activated Ionic/Angular 8添加基于 Button Activated Ionic/Angular 8 的 CSS
【发布时间】: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


【解决方案1】:

您可以使用索引作为您选择的按钮:

<div class="container">
   <div class="scroll" scrollX="true">
      <span *ngFor="let item of buttons; let i = index (click)="genreSelect(item, i)">
         <ion-button shape="round" [ngClass]="activeIndex == i ? 'buttonActive': ''"> 
            {{item.catName}}
         </ion-button>
      </span>
   </div>
</div>

.ts:

activeIndex = null;

genreSelect(item, index){
   this.activeIndex = index;
}

【讨论】:

  • 这适用于 ngclass 中的一些小改动 [ngClass]="activeIndex === i ? 'buttonActive': ''" 需要删除括号。否则它会给我语法错误。
猜你喜欢
  • 2023-03-17
  • 2021-04-05
  • 1970-01-01
  • 2011-08-23
  • 1970-01-01
  • 2015-03-19
  • 2017-02-08
  • 1970-01-01
  • 2021-06-06
相关资源
最近更新 更多