Dynamically adding SVG to DOM

后端 未结 1 480
余生分开走
余生分开走 2021-01-23 07:49

I have looked all over this site and the internet and I cant seem to find a way that I understand to add an svg to the dom using javascript. Can anyone help me please? The svg I

相关标签:
1条回答
  • 2021-01-23 07:55

    You can work with SVG elements like with a simple DOM structure.

    For example, you can edit it using .html() jQuery function:

    $("#mySvgContainer").html("<svg version=\"1.1\" id=\"Layer_1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\" width=\"450px\" height=\"450px\" viewBox=\"0 0 450 450\" style=\"enable-background:new 0 0 450 450;\" xml:space=\"preserve\"><style type=\"text/css\">.st0{fill:none;stroke:#000000;stroke-miterlimit:10;}</style><line class=\"path\" fill=\"none\" stroke=\"#000000\" x1=\"0\" y1=\"154.5\" x2=\"450\" y2=\"154.5\"/><line class=\"path\" fill=\"none\" stroke=\"#000000\" x1=450\" y1=\"304.5\" x2=\"0\" y2=\"304.5\"/><line class=\"path\" fill=\"none\" stroke=\"#000000\" x1=\"145.5\" y1=\"0\" x2=\"145.5\" y2=\"450\"/><line class=\"path\" fill=\"none\" stroke=\"#000000\" x1=\"295.5\" y1=\"450\" x2=\"295.5\" y2=\"0\"/></svg>");
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="mySvgContainer"></div>

    Also, you can dynamically create DOM SVG element and append it like you do it with HTML elements.

    0 讨论(0)
提交回复
热议问题