如何使用纯Javascript向嵌入式SVG添加元素?
我写了一篇小文章,看起来像这样:如何使用纯Javascript向嵌入式SVG添加元素?,javascript,html,svg,Javascript,Html,Svg,我写了一篇小文章,看起来像这样: <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>IGO – IRC Go</title> <link rel=
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>IGO – IRC Go</title>
<link rel="stylesheet" type="text/css" href="igo.css" />
<script type="text/javascript" src="igo.js"></script>
</head>
<body>
<h1 onclick="makeCircle()">IGO – IRC Go</h1>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" id="board"
width="4" height="4" viewBox="0 0 4 4">
<!-- content will be generated by script -->
</svg>
<div id="foo"></div>
</body>
</html>
function makeCircle() {
var circle = document.createElement("circle");
var board = document.getElementById("board");
circle.cx = 4;
circle.cy = 4;
circle.r = 4;
circle.fill = "lime";
board.appendChild(circle);
}
问题是:它不起作用;圆圈不显示。你能帮我吗?请查看以下URL: 您应该使用如下代码:
var c2 = document.createElementNS("http://www.w3.org/2000/svg", "circle");
c2.setAttribute("cx", "250");
c2.setAttribute("cy", "100");
c2.setAttribute("r", "60");
c2.setAttribute("fill", "#996699");
c2.setAttribute("stroke", "#AA99FF");
c2.setAttribute("stroke-width", "7");
mySvg.appendChild(c2);
您当前正在编辑DOM对象,而不是浏览器使用的属性
现场示例:请查看以下URL: 您应该使用如下代码:
var c2 = document.createElementNS("http://www.w3.org/2000/svg", "circle");
c2.setAttribute("cx", "250");
c2.setAttribute("cy", "100");
c2.setAttribute("r", "60");
c2.setAttribute("fill", "#996699");
c2.setAttribute("stroke", "#AA99FF");
c2.setAttribute("stroke-width", "7");
mySvg.appendChild(c2);
您当前正在编辑DOM对象,而不是浏览器使用的属性
实例:谢谢!我应该试试。在小提琴上增加了一个活生生的例子。谢谢!我应该试试。在小提琴上增加了活生生的例子。