2008-09-19 57 views
36

鑑於現有的有效SVG文檔,創建「信息彈出窗口」的最佳方式是什麼,以便當您懸停或點擊某些元素時(比方說)您彈出一個任意數量的框(即,不僅僅是單個工具提示)的額外信息?如何創建一個SVG「工具提示」框?

這應該至少在Firefox中正確顯示,並且如果圖像被柵格化爲位圖格式,它將不可見。

+0

莫賴斯,如果你縮小問題的一點可能會有所幫助。也許關於哪些技術可用以及需要支持哪些瀏覽器(Firefox和其他內容?)更具體一些?只是一個建議。 – 2008-09-19 15:27:23

+0

接受的答案現在已過時,但Neil Fraser的答案仍然正確。 – Craig 2014-12-21 23:39:26

回答

23
<svg> 
    <text id="thingyouhoverover" x="50" y="35" font-size="14">Mouse over me!</text> 
    <text id="thepopup" x="250" y="100" font-size="30" fill="black" visibility="hidden">Change me 
    <set attributeName="visibility" from="hidden" to="visible" begin="thingyouhoverover.mouseover" end="thingyouhoverover.mouseout"/> 
    </text> 
</svg> 

進一步的解釋可以找到here

+0

這似乎並不適用於Firefox 3.0.1 - 它應該是? – morais 2008-09-22 15:01:39

2

由於<set>元素不適用於Firefox 3,我認爲您必須使用ECMAScript。

如果添加下面的腳本元素到您的SVG:

<script type="text/ecmascript"> <![CDATA[ 

    function init(evt) { 
     if (window.svgDocument == null) { 
     // Define SGV 
     svgDocument = evt.target.ownerDocument; 
     } 
     tooltip = svgDocument.getElementById('tooltip'); 
    } 

    function ShowTooltip(evt) { 
     // Put tooltip in the right position, change the text and make it visible 
     tooltip.setAttributeNS(null,"x",evt.clientX+10); 
     tooltip.setAttributeNS(null,"y",evt.clientY+30); 
     tooltip.firstChild.data = evt.target.getAttributeNS(null,"mouseovertext"); 
     tooltip.setAttributeNS(null,"visibility","visible"); 
    } 

    function HideTooltip(evt) { 
     tooltip.setAttributeNS(null,"visibility","hidden"); 
    } 
    ]]></script> 

您需要添加onload="init(evt)"到SVG元素調用init()函數。

隨後,向SVG的結尾,添加工具提示文本:

<text id="tooltip" x="0" y="0" visibility="hidden">Tooltip</text> 

最後,每一個元素,你想擁有的鼠標懸停功能添加:

onmousemove="ShowTooltip(evt)" 
onmouseout="HideTooltip(evt)" 
mouseovertext="Whatever text you want to show" 

我已經用改進的功能寫了更詳細的解釋http://www.petercollingridge.co.uk/interactive-svg-components/tooltip

我還沒有包含多行工具提示,這將需要多個<tspan>元素和手動詞包裝。

45

2008年提出了這個問題。在這四年的時間裏,SVG已經迅速提高。現在,我意識到所有平臺都完全支持工具提示。使用<title>標記(而不是屬性),您將獲得原生工具提示。

下面是文檔: https://developer.mozilla.org/en-US/docs/SVG/Element/title

1

這應該工作:

nodeEnter.append("svg:element") 
    .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; }) 
    .append("svg:title") 
    .text(function(d) {return d.Name+"\n"+d.Age+"\n"+d.Dept;}); // It shows the tool tip box with item [Name,Age,Dept] and upend to the svg dynamicaly