我有一个基本上看起来像这样的javascript变量:
my_svg_image = '<circle cx="227.58331298828125" cy="102" r="3" style="fill:black;stroke-width:0" />';
Run Code Online (Sandbox Code Playgroud)
它是从我的数据库加载的.有没有办法可以解析该字符串并使用Javascript将其添加到DOM?我有svgweb设置,但看不出我怎么能解析这个字符串.是否有其他图书馆可能有所帮助?
你试过javascript的innerHTML属性吗?
编辑:您只能对html元素使用innerHTML属性,因此您可以使用包含整个svg图像的字符串将其添加到html元素。但是您无法将 svg 元素添加到现有 svg 元素。
例子:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN"
"http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg">
<head>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8"/>
<script type="text/javascript">
<![CDATA[
function test() {
var newsvg = document.getElementById("svg-wrapper");
var svgstr = '<svg:svg height="300" width="700" id="svg-container"><svg:circle cx="150px" cy="100px" r="30px" /></svg:svg>';
newsvg.innerHTML = svgstr;
}
]]>
</script>
<title>SVG DOM</title>
</head>
<body>
<div id="svg-wrapper"></div>
<input type="button" onclick="javascript:test();" value="generate svg"/><br/>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
如果你想向现有的内联 SVG 添加一个圆圈,你必须使用 DOM 方法添加它(并且可能首先解析你的字符串以提取所需的属性值)。