更改Ionic 4中toast消息的背景颜色

4

我该如何更改Toast消息的背景颜色?

我已经尝试过这个:但没有成功。这是因为shadow DOM效果造成的吗?

variable.scss

--background:red;

global.scss

ion-toast>.toast-wrapper {
    background-color: red !important;
}

.ts

  async showErrorToast(data: string) {
    const toast = await this.toastCtrl.create({
      message: data,
      duration: 3000000,
      position: 'bottom'
    });
    toast.present();
  }

enter image description here


如果您只尝试这个.toast-wrapper { background-color: red !important; },会发生什么? - Temani Afif
我已经尝试过了。但是它从未被应用。这是因为“Shadow DOM”吗?@TemaniAfif - Sampath
是的,这是因为阴影的原因,我注意到了。CSS应该添加在内部。 - Temani Afif
我怎么才能黑掉这个?@TemaniAfif - Sampath
6个回答

10

您可以在提示参数中设置颜色:

 const toastController = document.querySelector('ion-toast-controller');
 await toastController.componentOnReady();
 const toast = await toastController.create({
   showCloseButton: false,
   message: 'test toast message',
   position: 'top',
   duration: 2000,
   color: 'danger'
 });
 await toast.present();

1

首先像这样定义类:

.toast-bg {
background-color:red;
}

然后,将类作为参数传递给toast选项,如下所示:
{
    message: data,
    duration: 3000000,
    position: 'bottom',
    cssClass:'toast-bg'

}

1

请确保在公共的.scss文件中声明样式类。我认为在Ionic 3中它被称为app.scss,而在Ionic v4中则被称为global.scss


0

这个解决方案适用于Ionic v4和Ionic v6:

首先,使用Ionic属性“--background”定义您的背景颜色(类不需要在global.scss中定义)。

.toast-background {
    --background: rgb(175,175,175);
}

然后在启动toastController时引用新类

const toast = await this.toastCtrl.create({
    message: 'Message Here.',
    duration: 30000,
    cssClass: 'toast-background'
});
toast.present();

0
在创建 Toast 时添加 cssClass 属性,并将类名添加到其中。
 async showErrorToast(data: string) {
    const toast = await this.toastCtrl.create({
      message: data,
      duration: 3000000,
      position: 'bottom',
      cssClass: 'toast_style'
    });
    toast.present();
  }

添加样式类

.toast_style {
background-color:red;
}

在这里参考Ionic文档的toast toast


0

您可以使用应用程序颜色调色板中的颜色。默认选项包括:primarysecondarytertiarysuccesswarningdangerlightmediumdark

async showErrorToast(data: string) {
    const toast = await this.toastCtrl.create({
      ...
      color: 'primary'
    });
    toast.present();
  }

更多详细信息,请参阅 Ionic文档


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接