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

如何在SweetAlert2中修改标题的文本颜色?

修改SweetAlert2标题文本颜色的实现方法

有两种常用方案可实现需求,按需选择即可:

方案1:使用官方原生配置(最简单,推荐)

SweetAlert2 内置了titleColor配置项,直接在你的弹窗配置中添加该字段,赋值为你需要的颜色值即可,修改后的代码如下:

function CustomConfirm(title, message, type) {
    return new Promise((resolve) => {
        Swal.fire({
            title: title,
            text: message,
            icon: type,
            titleColor: '#d33', // 替换为你想要的任意颜色值,支持十六进制、rgb、颜色名等格式
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#6e7d88',
            confirmButtonText: 'Yes',
            cancelButtonText: "No"
        }).then((result) => {
            if (result.isConfirmed) {
                resolve(true);
            } else {
                resolve(false);
            }
        });
    });
}

方案2:自定义样式类(适合需要同时调整标题其他样式的场景)

如果需要同时修改标题的字体大小、字重、边距等更多样式,可以通过customClass配置自定义类名,再搭配CSS实现:

  1. 先修改JS配置,添加自定义类:
function CustomConfirm(title, message, type) {
    return new Promise((resolve) => {
        Swal.fire({
            title: title,
            text: message,
            icon: type,
            customClass: {
                title: 'my-swal-title' // 自定义的标题类名
            },
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#6e7d88',
            confirmButtonText: 'Yes',
            cancelButtonText: "No"
        }).then((result) => {
            if (result.isConfirmed) {
                resolve(true);
            } else {
                resolve(false);
            }
        });
    });
}
  1. 在全局CSS中添加对应样式规则:
.my-swal-title {
  color: #d33 !important; /* 自定义颜色,加!important可避免被默认样式覆盖 */
  font-size: 24px; /* 可额外添加其他样式 */
  font-weight: bold;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 13:48:03