【发布时间】:2011-10-05 14:57:36
【问题描述】:
我已经阅读了一些与此类似的问题,但我的代码无法正常工作。当用户单击 SVG 区域时,我想添加一个 SVG 元素。
这是我的带有 SVG 的 HTML5,它可以正确呈现:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.6.2.min.js"></script>
<script src="svgdraw.js"></script>
</head>
<body>
<svg id="canvas" width="500" height="500">
<circle cx="80" cy="80" r="50" fill="blue"/>
</svg>
</body>
</html>
这是在点击事件上执行的 JavaScript:
var svgDocument = document.getElementById('canvas');
var svgns = "http://www.w3.org/2000/svg";
var shape = svgDocument.createElementNS(svgns,"circle");
shape.setAttributeNS(null, "cx", 25);
shape.setAttributeNS(null, "cy", 25);
shape.setAttributeNS(null, "r", 20);
shape.setAttributeNS(null, "fill", "green");
document.getElementById('canvas').appendChild(shape);
在 Google Chrome 中,我收到一条错误消息,指出 createElementNS 不存在。但是,如果我删除所有NS 和null,我将无法正常工作。这样做的正确方法是什么?不同浏览器有区别吗?
【问题讨论】:
-
当我尝试复制您的问题时,我遇到了 svgDocument 未定义。知道为什么会这样吗?
-
我虽然 html5 不再需要命名空间了?!
标签: javascript html svg createelement