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

如何在Bootstrap tooltip中使用background-image并使其正常显示?

Bootstrap工具提示中background-image无法显示的问题

我尝试在Bootstrap工具提示(tooltip)中添加一个使用background-image属性的元素,但图片无法显示。相关代码如下:

<div class="big-panel">
    <a href="#" data-bs-toggle="tooltip" data-bs-html="true" data-bs-title="Background image: <span style='display: block; background-size: cover;width: 32px; height: 32px; background-image: url(test/image.png)'></span> <br>Regular image: <img src='test/image.png'>">Hover me for testing</a>
</div>

问题效果示意图:
问题效果示意图

我在同一个工具提示中添加了常规的<img>标签,它能正常显示,但background-image属性始终无法生效,请问这是否可以实现?


可以实现,问题出在Bootstrap的样式过滤机制

Bootstrap 5+的工具提示默认会对data-bs-title里的内联样式做清理(sanitize),background-image属于默认被过滤的样式属性,所以写了也不会生效;而<img>的src属性不在过滤列表里,因此能正常加载图片。

解决方法

方法1:全局允许background-image样式

在初始化工具提示之前,修改全局的允许规则,让background-image通过过滤:

// 扩展默认允许的样式列表
const defaultAllowStyles = bootstrap.Tooltip.Default.allowList.style || [];
bootstrap.Tooltip.Default.allowList.style = [...defaultAllowStyles, 'background-image'];

// 初始化页面上所有工具提示
document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(el => {
    new bootstrap.Tooltip(el);
});

方法2:给单个工具提示单独配置

如果只需要当前这个工具提示生效,单独设置它的允许规则:

const targetTooltip = document.querySelector('a[data-bs-toggle="tooltip"]');
new bootstrap.Tooltip(targetTooltip, {
    allowList: {
        style: ['background-image', 'display', 'background-size', 'width', 'height']
    }
});

额外说明

你的图片路径test/image.png是没问题的(因为<img>能正常显示),不需要修改路径,只要解决样式过滤的问题即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 02:16:19