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

FullCalendar 6 + Bootstrap5:动态修改Tooltip背景色问题

FullCalendar + Bootstrap 5 实现Tooltip与事件同色的问题解决

问题场景

使用FullCalendar时已为事件设置自定义颜色,希望事件对应的Tooltip背景色、文本色与事件保持一致,但此前在FullCalendar 2.9 + Bootstrap 3环境下可用的代码,在当前FullCalendar + Bootstrap 5.3环境中失效,Tooltip始终显示黑色。

原失效代码:

eventDidMount: function (arg) {
    // 部分代码
    var tooltipHtml = "<div style=\"background-color:" + arg.event.extendedProps.backgroundColor + ";" + "color:" + arg.event.extendedProps.textColor + ";" + "\">" +
                "<b>" + arg.event.title 
                + "</b></div>";

     var tooltipOptions = {
                    "html": true, // 允许Tooltip中使用HTML
                    "title": tooltipHtml,
                    "container": "body" // 避免Tooltip被头部遮挡
                };
}

环境说明:已配置themeSystem: 'bootstrap5',且在FullCalendar.js之前引入了Bootstrap 5.3 bundle js及图标。

原因分析

Bootstrap 5的Tooltip默认会对内容进行sanitize(内容过滤)处理,虽然div标签在默认允许列表内,但内联style中的背景色、文本色属性会被过滤,导致自定义样式不生效。此外,颜色为用户运行时动态定义,无法通过提前编写CSS类的方式解决。

解决方案

1. 快速生效方案

在Tooltip配置中添加sanitize: false,关闭内容过滤机制,让内联样式正常生效,Tooltip即可渲染出与事件一致的颜色:

eventDidMount: function (arg) {
    var tooltipHtml = "<div style=\"background-color:" + arg.event.extendedProps.backgroundColor + ";color:" + arg.event.extendedProps.textColor + ";\">" +
                "<b>" + arg.event.title + "</b></div>";

     var tooltipOptions = {
                    html: true,
                    title: tooltipHtml,
                    container: "body",
                    sanitize: false // 关闭内容过滤,使内联样式生效
                };
    // 记得初始化Tooltip:$(arg.el).tooltip(tooltipOptions);
}

2. 更安全的方案(推荐)

不直接关闭sanitize,而是自定义允许的属性列表,仅放开需要的样式规则,降低安全风险:

// 扩展Bootstrap Tooltip默认允许列表,允许div标签使用style属性
$.fn.tooltip.Constructor.Default.allowList.div = ['style'];

// 或者自定义sanitize函数,仅保留background-color和color样式
var customSanitize = function(content) {
    return content.replace(/style="[^"]*"/g, function(match) {
        // 只保留背景色和文本色样式
        return match.replace(/(background-color|color):[^;]+;/g, function(style) {
            return style;
        });
    });
};

// 在Tooltip配置中使用自定义sanitize函数
var tooltipOptions = {
    html: true,
    title: tooltipHtml,
    container: "body",
    sanitizeFn: customSanitize
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 15:53:33