簡體   English   中英

我可以將復雜的 HTML 與 Twitter Bootstrap 的工具提示一起使用嗎?

[英]Can I use complex HTML with Twitter Bootstrap's Tooltip?

如果我查看官方文檔,我可以看到一個名為 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 插入工具提示”,但類型是 boolean。如何在工具提示中使用復雜的 html?

此參數只是關於是否要將復雜的html用於工具提示。 將其設置為true ,然后將html命中為標記的title屬性。

在這里看到這個小提琴 - 我已經通過<a>標簽中的data-html="true"將html屬性設置為true,然后僅在html ad hoc中添加作為示例。

正常情況下,使用data-original-title

HTML:

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

使用Javascript:

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

html參數指定工具提示文本應如何轉換為DOM元素。 默認情況下,Html代碼在工具提示中轉義以防止XSS攻擊。 假設您在自己的網站上顯示用戶名,並在工具提示中顯示小型生物。 如果html代碼沒有被轉義並且用戶可以自己編輯bio,則他們可以注入惡意代碼。

避免將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內容,並根據需要激活任意數量的工具提示。

在codepen上現場演示

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”選項設置為true。 實際的html由選項“title”決定(不應設置鏈接的title屬性)

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

現場樣本

從 bootstrap 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!
     })
});

對於 bootstrap 5,您可以使用data-bs-html="true"和標題標簽data-bs-original-title="Tooltip Title"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM