10

我一直在尝试使用 HTML 中的 javascript 为 svg 操作打个招呼。我编写了以下代码,虽然它生成了正确的 html,但我在浏览器中看不到任何输出,也看不到任何错误。

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var svg1 = document.createElement("svg");
svg1.setAttribute("height",200);
svg1.setAttribute("width",500);
document.body.appendChild(svg1);
var circles = document.createElement("circle");
circles.setAttribute("cx",20);
circles.setAttribute("cy",20);
circles.setAttribute("r",20);
svg1.appendChild(circles);
</script>
</body>
</html>

我哪里错了?提前致谢。

4

1 回答 1

31

SVG 元素需要使用 SVG XML 命名空间创建。您可以使用createElementNS和使用http://www.w3.org/2000/svg命名空间来做到这一点:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var svg1 = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg1.setAttribute("height",200);
svg1.setAttribute("width",500);
document.body.appendChild(svg1);
var circles = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circles.setAttribute("cx",20);
circles.setAttribute("cy",20);
circles.setAttribute("r",20);
svg1.appendChild(circles);
</script>
</body>
</html>
于 2013-10-09T19:46:51.453 回答