简体   繁体   中英

setting color on ion-button cancel hover

I am making a button bar for my app and I am trying to change color of button by its state (false, true).

Right now the button start at green color while hover is light green when clicked its white, after I click it the button become white and the hover is no longer working (nothing happens on hover). I have tried changing the class of the button via DOM but the button disappear.

HTML

    <ion-button *ngIf="getAudio() !== undefined" class="musicIcon" id="musicIcon" fill="clear" button (click)="musicToggle()">
      <audio id="backgroundAudio" src="{{getAudio()}}"></audio>
      <ion-icon slot="icon-only" name="musical-notes"></ion-icon>
    </ion-button>

CSS

.musicIcon{
    --color: #047E00;
    --color-hover: #A9FEA6;
}

JS

  musicToggle() {
    this.musicState = !this.musicState;
    const icon = document.getElementById("musicIcon");
    const audio = document.getElementById("backgroundAudio") as any;
    if (this.musicState) {
      audio.muted = true;
      icon.style.color = 'white';
    } else {
      audio.muted = false;
      icon.style.color = '#047E00';
    }
  }

I think it would make sense not to change the styles in your javascript logic, but leave as much of the look to Ionic as possible. The main problem seems to be, that you overwrite the color-style with a static value, where Ionic would have used the value of --color or --color-hover dynamically.

First of all, do you know Ionic's theming ? If you define your green as the primary color, your <ion-button> s will have the color per default and you do not have to write a custom class.

If you want the button to have a different color if this.musicState === true , the simplest way would be to define that directly in the template via color -attribute:

 <ion-button *ngIf="getAudio() !== undefined" [color]="musicState ? 'light' : 'primary'" class="musicIcon" id="musicIcon" fill="clear" button (click)="musicToggle()">
  <audio id="backgroundAudio" src="{{getAudio()}}"></audio>
  <ion-icon slot="icon-only" name="musical-notes"></ion-icon>
</ion-button>

With this adjustment, you can remove your CSS-class and your musicToggle()-function will be just the following lines:

  musicToggle() {
    this.musicState = !this.musicState;
    const icon = document.getElementById("musicIcon");
    const audio = document.getElementById("backgroundAudio") as any;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM