javascript - 向 .textContent 文本添加换行符

标签 javascript html css svg tooltip

我正在尝试显示超过 2 行的工具提示文本,但似乎没有任何效果。 我有一个带有文本元素的 SVG,用于显示带有管理工具提示的 ecmascript 的工具提示。 我在行中尝试了几个选项

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

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

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

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

最佳答案

尝试添加 <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);

关于javascript - 向 .textContent 文本添加换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36475971/

相关文章:

javascript - 如何为iframe的内部html编写css

javascript - 如何使用纯 JavaScript 获取 div 内图像集的 src 值?

javascript - 降低图像分辨率/尺寸以显示为预览

javascript - 启用插件后更改 TinyMCE HTML

javascript - Carousel 使用 JS 管理状态并使用 CSS 制作动画

javascript - 如何将 Quickblox 与 angularjs 集成?

javascript - 无法调用undefined的save方法。蒙古人

javascript - 页脚使用https://www.tesla.com/charging使用什么方法?

html - Bootstrap 表 : Grid system - How to put image with width in different rows and the same column

css - 如何设置在 Visual Studio 中读取纯文本的语言