【问题标题】:Unable to append svg element to svg root无法将 svg 元素附加到 svg 根
【发布时间】:2016-09-30 22:02:23
【问题描述】:

我想使用鼠标悬停事件向我现有的 svg 添加一个文本元素。我认为代码通常可以正常工作,但我无法将创建的文本元素附加到现有的 svg 文件(根)。我试图以一种我也可以在 stackoverlow 上找到它的方式来做到这一点,但它对我不起作用。 var root = doc.documentElementvar root = doc.rootElement 都不起作用。在创建元素时使用 svgNS 或 null 也没有区别。

这是我的代码:

<script type="text/ecmascript">
    <![CDATA[function showText(evt) { 
    var doc = evt.target.ownerDocument; 
    var root = doc.documentElement; 
    var text = doc.createElementNS(null, "text"); 
    text.setAttributeNS(null, "x", "10"); 
    text.setAttributeNS(null, "y", "30"); 
    text.setAttributeNS(null, "font-size", "12"); 
    var textNode = doc.createTextNode("test"); 
    text.appendChild(textNode); 
    root.appendChild(text);  
    }]]>
</script>

我的 svg 的完整代码:

<?xml version="1.0" encoding="UTF-8" ?>
<svg xmlns="http://www.w3.org/2000/svg" style="stroke:black" height="600" width="800">
  <rect width="800" x="0" y="0" height="600" style="fill:none" />
  <rect width="800" x="0" id="textbox" y="540" height="60" style="fill:none" />
  <rect width="720" x="40" y="30" height="480" style="fill:none" />
  <line y2="510" x1="40" x2="760" y1="510" />
  <line y2="510" x1="40" x2="40" y1="30" />
  <text font-size="12" x="40" y="530">Time (X)</text>
  <text font-size="12" x="5" y="20">Data (Y)</text>
  <polyline style="stroke:black;fill:none;" points="91.84,217.19189757859385 143.68,323.2917668597486 195.52,235.86502103932202 247.36,43.359991864346625 299.2,202.8 351.04,315.903272925833 402.88,160.41241257803188 454.72,157.66691947582518 506.56,387.2047460928005 558.4,183.60000000000002 610.24,260.73963745895736 662.08,59.445816214522495 713.9200000000001,283.88097314947527 "
  stroke-width="2" />
  <script type="text/ecmascript">
    < ![CDATA[function showText(evt) {
      var doc = evt.target.ownerDocument;
      var root = doc.documentElement;
      var text = doc.createElementNS(null, "text");
      text.setAttributeNS(null, "x", "10");
      text.setAttributeNS(null, "y", "30");
      text.setAttributeNS(null, "font-size", "12");
      var textNode = doc.createTextNode("test");
      text.appendChild(textNode);
      root.appendChild(text);
    }]] >
  </script>
  <circle id="circle" text="Dies ist ein Test" r="10" cx="400.0" onmouseover="showText(evt)" cy="510">Dies ist ein Test</circle>
</svg>

【问题讨论】:

    标签: javascript xml events svg mouseover


    【解决方案1】:

    SVG 元素必须在 SVG 命名空间中创建,所以您需要这样:

    var text = doc.createElementNS("http://www.w3.org/2000/svg", "text");
    

    您的代码 sn-p 具有的 CDATA 开始/结束部分标记中也不能有空格(但您的原始代码摘录没有)。

    【讨论】:

    • 试过了,不幸的是没有区别。编辑:好的,命名空间就在这一行 - 在“text.setAttributeNS”中仍未使用,它可以工作。非常感谢!
    • 假设我将它作为独立的 SVG 文件运行,在本地使用该/那些更改为我工作。它不能作为堆栈 sn-p 工作,因为根元素是那里的 html 页面。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    • 2021-10-30
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    相关资源
    最近更新 更多