简体   繁体   中英

Add new line character to .textContent text

I am trying to display a tooltip text over 2 lines but nothing seems to be working. I have an SVG with a text element for displaying a tooltip with an ecmascript managing the tooltip. I have tried several options in the line

    tooltip.textContent = " Text = " + id  + " <br/> Result =" + result; 

“\\n”, “\\n\\n”, '\\\\\\n', style=" white-space: pre;", String.fromCharCode(13)

but the tooltip will not split into 2 lines. Any suggestions please.

    <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>

Try adding <tspan> elements inside the tooltip with different y positions, as pointed in Example 3 from here: http://www.w3schools.com/svg/svg_text.asp

More precisely, replace the line tooltip.textContent = ... with

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM