You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SweetAlert2如何修改弹窗标题与正文文字的颜色?

方案说明

实现修改标题和正文文字颜色的需求不强制使用customClass参数,SweetAlert2已经提供了内置配置参数可以直接实现需求。


方案一:使用内置参数(无需额外编写CSS)

直接在Swal.fire的配置项中添加两个参数即可:

  • titleColor:控制标题文字颜色
  • color:控制正文(text/html内容)的文字颜色

修改后的完整代码示例:

Swal.fire({
  icon: 'warning',
  title: 'Attention...',
  text: 'Change color of this text',
  background: '#1e2122',
  confirmButtonColor: '#ff6600',
  confirmButtonText: 'OK',
  iconColor: '#ff6600',
  // 新增以下两个配置修改文字颜色,色值可自行调整
  titleColor: '#ffffff', 
  color: '#e0e0e0'
})

方案二:使用customClass(适合需要多维度自定义样式的场景)

如果还有字号、行高等其他样式调整需求,可以通过自定义类实现:

  1. 先在CSS文件中添加自定义样式:
/* 自定义标题样式 */
.swal-title-custom {
  color: #ffffff;
  font-size: 22px;
}
/* 自定义正文样式 */
.swal-content-custom {
  color: #e0e0e0;
  line-height: 1.5;
}
  1. 在Swal配置中关联自定义类:
Swal.fire({
  icon: 'warning',
  title: 'Attention...',
  text: 'Change color of this text',
  background: '#1e2122',
  confirmButtonColor: '#ff6600',
  confirmButtonText: 'OK',
  iconColor: '#ff6600',
  customClass: {
    title: 'swal-title-custom',
    htmlContainer: 'swal-content-custom'
  }
})

之前查到的方案失效大概率是SweetAlert2版本差异导致,上述方案适配v11及以上的主流版本,使用旧版本的话可以先升级到最新稳定版再使用以上配置。

内容的提问来源于stack exchange,提问作者Maxime

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 10:06:02