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