将新行字符添加到.textContent文本

时间:2016-04-07 12:18:52

标签: javascript html5 css3 svg tooltip

我试图在2行显示工具提示文本,但似乎没有任何工作。 我有一个带有文本元素的SVG,用于显示带有管理工具提示的ecmascript的工具提示。 我在行

中尝试了几个选项
    tooltip.textContent = " Text = " + id  + " <br/> Result =" + result; 

“\ n”,“\ n \ n”,&#39; \\\ n&#39;,style =&#34; white-space:pre;&#34;, 使用String.fromCharCode(13)

但工具提示不会分成2行。 请提出任何建议。

    <svg ….>
     <script type="text/ecmascript">
<![CDATA[
   function init(evt) {
    if ( window.svgDocument == null ) {
       svgDoc = evt.target.ownerDocument;   
    }
    theSvgElement = document.getElementById("svg");
    tooltip = svgDoc.getElementById('tooltip');             
       }          
   function ShowTooltip(id) { 
    result = getResult();   
    tooltip.setAttributeNS(null,"visibility","visible");
    tooltip.textContent = " Text = " + id  + " \n Result =" + result; 
        }
   function HideTooltip() {  
    tooltip.setAttributeNS(null,"visibility","hidden");
        } 
]]> 
    </script>   
      <g> 
   <circle 
     r="40" 
     cy="200"
     cx="300" 
      fill="#00b300" 
      onmouseout="HideTooltip()"
      onmouseover="ShowTooltip('CD.02.02.02')"/>  
      </g>
       <text class="tooltip" id="tooltip" x="20" y="20" 
           style="font-family: Times New Roman; font-size: 80; fill: #000000; white-space: pre;" 
           visibility="hidden"> Hover to read the text. 
    </text>
    </svg>

1 个答案:

答案 0 :(得分:0)

尝试在工具提示中添加<tspan>个不同y位置的元素,如示例3中所示:http://www.w3schools.com/svg/svg_text.asp

更准确地说,将行tooltip.textContent = ...替换为

tooltip.textContent = "";

var tspan1 = document.createElementNS("http://www.w3.org/2000/svg", 'tspan');
txtnode1 = document.createTextNode("Text = " + id);
tspan1.appendChild(txtnode1);
tspan1.setAttribute("x",20);
tspan1.setAttribute("y",30);

var tspan2 = document.createElementNS("http://www.w3.org/2000/svg", 'tspan');
txtnode2 = document.createTextNode("Result =" + result);
tspan2.appendChild(txtnode2);
tspan2.setAttribute("x",20);
tspan2.setAttribute("y",60);

tooltip.appendChild(tspan1);
tooltip.appendChild(tspan2);
相关问题