Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用JavaScript设置SVG元素的大小?_Javascript_Svg - Fatal编程技术网

如何使用JavaScript设置SVG元素的大小?

如何使用JavaScript设置SVG元素的大小?,javascript,svg,Javascript,Svg,我正在编写一段代码来创建一个新的SVG元素,但是设置宽度和高度属性时遇到了问题 var svg = document.createElement("svg"); while(!svg); // wait for it svg.setAttribute("width", "100"); svg.setAttribute("height", "100"); document.body.appendChild(svg); 检查后,元素的两个属性设置正确,并且.getAttribute()方法返回

我正在编写一段代码来创建一个新的SVG元素,但是设置宽度和高度属性时遇到了问题

var svg = document.createElement("svg");
while(!svg); // wait for it

svg.setAttribute("width", "100");
svg.setAttribute("height", "100");

document.body.appendChild(svg);
检查后,元素的两个属性设置正确,并且
.getAttribute()
方法返回正确的值,但是当我将光标悬停在元素上时,它显示为
svg 0×0
。我可能错过了一些非常明显的东西,但我似乎不知道它是什么。有什么想法吗?

你可以试试这段代码

函数svg(){
//创建svg元素
const svg1=document.createElements(“http://www.w3.org/2000/svg“,“svg”);
//设置宽度和高度
svg1.setAttribute(“宽度”、“500”);
svg1.setAttribute(“高度”、“500”);
//创建一个圆
const cir1=document.createElements(“http://www.w3.org/2000/svg“,”圆圈“);
cir1.setAttribute(“cx”、“200”);
cir1.setAttribute(“cy”,“200”);
cir1.setAttribute(“r”、“200”);
cir1.设置属性(“填充”、“红色”);
//把它装在容器上
svg1.appendChild(cir1);
//将容器附在文件上
document.getElementById(“svg54583”).appendChild(svg1);
}
svg()

尝试直接设置,而不是使用
svg.width=100作为属性非常感谢,我不知道用
createElements()
替换
createElements()
可能会有所不同。使用指定的命名空间URI和限定名称创建元素。要在不指定命名空间URI的情况下创建元素,请使用createElement()方法。欲了解更多详情,请访问