以下是我正在玩的jsfiddle示例:
var svgNS = "http://www.w3.org/2000/svg";
var newRect = document.createElementNS(svgNS,"rect");
newRect.setAttributeNS(null,"width",Math.random() * 100);
newRect.setAttributeNS(null,"height",Math.random() * 100);
newRect.setAttributeNS(null,"x",Math.random() * 250);
newRect.setAttributeNS(null,"y",Math.random() * 180 + 60);
newRect.setAttributeNS(null,"fill-opacity",Math.random());
var red = Math.round(Math.random() * 255);
var green = Math.round(Math.random() * 255);
var blue = Math.round(Math.random() * 255);
newRect.setAttributeNS(null,"fill","rgb("+ red +","+ green+","+blue+")");
document.getElementsByTagName("svg")[0].appendChild(newRect);
但是,我无法通过在控制台中编写以下代码来创建SVG元素:
var svgNS = "http://www.w3.org/2000/svg";
var newRec = document.createElementNS(svgNS,"rect");
newRec.setAttributeNS(null,"fill","black");
newRec.setAttributeNS (null, "width", "100");
newRec.setAttributeNS (null, "height", "50");
newRec.setAttributeNS (null, "x", "50");
newRec.setAttributeNS (null, "y", "50");
var prevRec = document.getElementsByTagName ("rect")[0];
var parent = prevRec.parentNode;
parent.insertBefore (newRec, prevRec);