svg innerHTML in firefox can not display

自作多情 提交于 2019-12-02 00:41:58

问题


i use innerHTML to add svg element,it works fine in chrome but in firefox it can not display; thanks so much for any ansower

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

回答1:


A workaround is to add the innerHTML code as HTML, and not SVG. You can do that simply by using a <div> (instead of <svg>) in your HTML code as the placeholder, and insert the full SVG via innerHTML.

Replace:

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

with

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

And wrap your innerHTML string within an <svg> element:

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

This should work in both Chrome and Firefox. Here's a JSFiddle.



来源:https://stackoverflow.com/questions/23003278/svg-innerhtml-in-firefox-can-not-display

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!