繁体   English   中英

将SVG动态添加到DOM

[英]Dynamically adding SVG to DOM

我在这个网站和互联网上四处张望,似乎无法找到一种方法,可以使用javascript在dom中添加svg。 谁能帮我吗? 我要在下面添加的svg。

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

您可以像使用简单的DOM结构一样使用SVG元素。

例如,您可以使用.html() jQuery函数对其进行编辑:

 $("#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> 

另外,您可以动态创建DOM SVG元素并像使用HTML元素一样附加它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM