2015-09-28 82 views
1

我已經看了遍佈這個網站和互聯網,我似乎找不到一種方式,我明白要添加一個SVG使用JavaScript的DOM。任何人都可以幫助我嗎?我想在下面添加svg。動態添加SVG到DOM

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

回答

1

您可以像使用簡單的DOM結構一樣使用SVG元素。

例如,您可以使用jQuery的.html()功能,可以編輯:

$("#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元素做。