【问题标题】:svg innerHTML in firefox can not displayFirefox 中的 svg innerHTML 无法显示
【发布时间】:2014-05-25 01:25:26
【问题描述】:

我使用 innerHTML 添加 svg 元素,它在 chrome 中运行良好,但在 firefox 中无法显示;非常感谢您的任何回答

    <!DOCTYPE html>
    <html>
    <head>
        <title>SVGInnerHTML demo</title>
        <meta charset="utf-8" />
        <script src="svginnerhtml.js"></script>
        <script>
        alter  = function () {
            var svg = document.getElementById('container');

            svg.innerHTML   = '<rect width="100" height="60" fill="green" />'
                            + '<circle cx="10" cy="19" r="20" fill="blue"></circle>'
                            + '<text x="15" y="20" fill="white">hello world</text>'
                            + '<g transform="translate(0, 70)"><rect width="100" height="20" fill="yellow" /></g>';
        }
        </script>
    </head>

    <body>

    <svg id="container" width="100px" height="100px" http://www.w3.org/2000/svg>

    </svg>

    <p>
    <button onclick="alter()">set .innerHTML</button>
    <button onclick="alert(document.getElementById('container').innerHTML)">get .innerHTML</button>
    </p>
    </body>
    </html>

【问题讨论】:

  • 从 Firefox 36 开始,这应该可以正常工作。

标签: firefox svg innerhtml


【解决方案1】:

一种解决方法是将 innerHTML 代码添加为 HTML,而不是 SVG。您只需在 HTML 代码中使用 &lt;div&gt;(而不是 &lt;svg&gt;)作为占位符,然后通过 innerHTML 插入完整的 SVG。

替换:

<svg id="container" width="100px" height="100px">
</svg>

<div id="container" style="width: 100px; height: 100px">
</div>

并将您的 innerHTML 字符串包装在 &lt;svg&gt; 元素中:

var svg = document.getElementById('container');
svg.innerHTML   = '<svg><rect width="100" height="60" fill="green" />'
                + '<circle cx="10" cy="19" r="20" fill="blue"></circle>'
                + '<text x="15" y="20" fill="white">hello world</text>'
                + '<g transform="translate(0, 70)">'
                + '<rect width="100" height="20" fill="yellow" /></g></svg>';

这应该适用于 Chrome 和 Firefox。这是JSFiddle

【讨论】:

  • 如你所说;我将我的代码更改为var tempDiv = document.createElement("div"); tempDiv.innerHTML = "&lt;svg&gt;"+svgEles+"&lt;/svg&gt;" var svgNodes = Array.prototype.slice.call(tempDiv.childNodes[0].childNodes); svgNodes.forEach(function(el){ container.appendChild(el); }); 这个工作在 chrome 和 firefox 中;并且很容易修复我的旧代码谢谢!
猜你喜欢
  • 2018-03-11
  • 2015-05-01
  • 2014-03-06
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
  • 1970-01-01
  • 2013-04-11
相关资源
最近更新 更多