为 ion-toast 组件和阴影部分的按钮应用不同的样式

问题描述 投票:0回答:2

我正在使用 Ionic 创建一个应用程序,并且正在使用带有两个按钮的 toast 组件。 我必须为每个按钮创建不同的样式。

我的代码是这样的:

import { Component } from '@angular/core';
import { ToastController } from '@ionic/angular';

@Component({
  selector: 'toast-example',
  templateUrl: 'toast-example.html',
  styleUrls: ['./toast-example.css'],
})
export class ToastExample {

  constructor(public toastController: ToastController) {}

  async presentToast() {
    const toast = await this.toastController.create({
      message: 'Your settings have been saved.',
      duration: 2000
    });
    toast.present();
  }

  async presentToastWithOptions() {
    const toast = await this.toastController.create({
      header: 'Toast header',
      message: 'Click to Close',
      position: 'top',
      buttons: [
        {
          side: 'start',
          icon: 'star',
          text: 'Favorite',
          handler: () => {
            console.log('Favorite clicked');
          }
        }, {
          text: 'Done',
          role: 'cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        }
      ]
    });
    await toast.present();

    const { role } = await toast.onDidDismiss();
    console.log('onDidDismiss resolved with role', role);
  }

}

我想这样做:

ion-toast::part(button):first-of-type {
  --button-color: green !important;
}
ion-toast::part(button):nth-of-type(2) {
  --button-color: red !important;
}

但它不起作用:(

在这种情况下,有没有办法将样式应用于每个按钮?

提前致谢。

javascript css angular ionic-framework
2个回答
1
投票

不可能通过 css 对两个按钮使用不同的样式,但是你可以使用一点 JavaScript 来实现这一点。

将自定义类放入 toast 中

cssClass: 'toast-custom-class'

使用 cssClss

first-button
second-button

在两个按钮上放置自定义类

然后像吐司一样

await toast.present().then(() => {
  const toasts = document.getElementsByClassName('toast-custom-class');
  const shadow = toasts[0].shadowRoot;
  const childNodes = Array.from(shadow.childNodes);
  childNodes.forEach((childNode: any) => {
     const firstButton = childNode.getElementsByClassName('first-button');
     firstButton[0].setAttribute( 'style', 'color: red !important' );
     const secondButton = childNode.getElementsByClassName('second-button');
     secondButton[0].setAttribute( 'style', 'color: green !important' );
  });
});

0
投票

您可以更改颜色或样式,将

role:"string"
分配给 IonToast 中的不同按钮,然后使用 css 中的
::part(button "string")
选择器来更改其样式

例如:

ion-toast.eraseToast::part(button) {
  font-family: var(--customFont);
  color: #ff5858;
}

ion-toast.eraseToast::part(button cancel) {
  color: rgb(255, 255, 255);
}
<IonToast trigger='erasebutton'icon={trash} cssClass={"eraseToast"}  message={"Clear the counter?"} 
 buttons={[ {text:"Clear" ,role:"clear",handler()
  {erase()} },
 {text: "Dismiss",role:"cancel", handler() { eraseButtonItem?.classList.remove("selected") },} ]}>

</IonToast>

结果: https://i.stack.imgur.com/8KKVG.png

© www.soinside.com 2019 - 2024. All rights reserved.