我可以在 Bootstrap 的工具提示中使用复杂的 HTML 吗?

如果我检查 正式文件,我可以看到一个称为 HTML 的属性:

Name    |    Type       |    default  |    Description
----------------------------------------------------------------------------
html    |    boolean    |    false    |    Insert html into the tooltip.
If false, jquery's text method
will be used to insert content
into the dom. Use text if you're
worried about XSS attacks.

它说,“将 html 插入到工具提示中”,但是类型是布尔型的。如何在工具提示中使用复杂的 html?

201977 次浏览

这个参数只是关于是否要在工具提示中使用复杂的 html。将其设置为 true,然后将 html 命中到标记的 title属性中。

看看这个小提琴 给你-我已经通过 <a>标签中的 data-html="true"将 html 属性设置为 true,然后作为一个示例添加到 html 中。

和往常一样,使用 data-original-title:

网址:

<div rel='tooltip' data-original-title='<h1>big tooltip</h1>'>Visible text</div>

Javascript:

$("[rel=tooltip]").tooltip({html:true});

Html 参数指定如何将工具提示文本转换为 DOM 元素。默认情况下,Html 代码在工具提示中转义,以防止 XSS 攻击。假设您在站点上显示了一个用户名,并在工具提示中显示了一个小的简介。如果 html 代码没有逃脱,用户可以自己编辑生物,他们可以注入恶意代码。

设置“ html”选项为真,如果你想有 html 到工具提示。实际的 html 由选项“ title”决定(不应该设置链接的 title 属性)

$('#example1').tooltip({placement: 'bottom', title: '<p class="testtooltip">par</p>', html: true});

活体样本

html数据属性完全按照它在文档中所说的那样做。试试这个小例子,不需要 JavaScript (分成几行以便澄清) :

<span rel="tooltip"
data-toggle="tooltip"
data-html="true"
data-title="<table><tr><td style='color:red;'>complex</td><td>HTML</td></tr></table>"
>
hover over me to see HTML
</span>


JSFiddle 演示:

避免将 html 插入到 资料标题中的另一个解决方案是创建带有 html 内容的独立 div,并在创建工具提示时引用这个 div:

<!-- Tooltip link -->
<p><span class="tip" data-tip="my-tip">Hello world</span></p>


<!-- Tooltip content -->
<div id="my-tip" class="tip-content hidden">
<h2>Tip title</h2>
<p>This is my tip content</p>
</div>


<script type="text/javascript">
$(document).ready(function () {
// Tooltips
$('.tip').each(function () {
$(this).tooltip(
{
html: true,
title: $('#' + $(this).data('tip')).html()
});
});
});
</script>

通过这种方式,您可以创建复杂的可读 html 内容,并激活任意数量的工具提示。

现场演示

从引导程序5开始,在配置工具提示时,只需将其内容指定为 html DOM 节点即可。样本配置..。

// setup tools tips trigger
const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
const tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new Tooltip(tooltipTriggerEl, {
html: true // <- this should do the trick!
})
});