javascript - 动态地将 SVG 添加到 DOM

标签 javascript jquery svg

我浏览了这个网站和互联网,但我似乎无法找到一种我理解的使用 javascript 将 svg 添加到 dom 的方法。有人可以帮我吗?我想在下面添加它的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 元素一样。

关于javascript - 动态地将 SVG 添加到 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32816428/

相关文章:

javascript - 显示多组按钮中的当前按钮

javascript - 如何检查属性值

jquery - 使用 HTML 和 JQuery 创建可编辑列表

css - 如何使用 webpack 从 MDL 获取 svg

android - Vector Asset Studio 正在将彩色 .svg 文件导入为黑白

javascript - 使用Javascript函数将td的onclick设置为null

javascript;在数组中存储值

javascript - 在 float 条形图中同时显示悬停和旋转刻度 90 度

jquery - 如果找到特定的 td 类,如何添加标签来换行表行

html - 可以在 SVG 中将 &lt;!-- comment --> 作为第一行吗?