如何在使用JavaScript创建的SVG元素上设置viewBox?

如何在使用JavaScript创建的SVG元素上设置viewBox?,javascript,html,svg,Javascript,Html,Svg,当我在DOM中已经存在的SVG元素上使用setAttribute('viewBox')时,它会被正确设置(大写字母“b”) 当我在JavaScript中创建SVG元素并在其中添加“viewBox”属性时。它以所有小写字母结束在DOM中 为什么会这样 document.querySelector('#circle svg').setAttribute('viewBox','190 20'); 让svg=document.createElement('svg'), 圆圈=document.crea

当我在DOM中已经存在的SVG元素上使用setAttribute('viewBox')时,它会被正确设置(大写字母“b”)

当我在JavaScript中创建SVG元素并在其中添加“viewBox”属性时。它以所有小写字母结束在DOM中

为什么会这样

document.querySelector('#circle svg').setAttribute('viewBox','190 20');
让svg=document.createElement('svg'),
圆圈=document.createElement(“圆圈”);
circle.setAttribute('cx',200);
circle.setAttribute('cy',200);
圆圈.setAttribute('r',10);
setAttribute('viewBox','190 20');
svg.appendChild(圆);
document.body.appendChild(svg);
//document.querySelector(“#圈生成svg”).setAttribute('viewBox','190 20')
svg{
边框:2个虚线#666;
宽度:200px;
高度:200px;
}
动态添加viewBox属性的现有svg:


生成的svg带有动态添加的viewBox属性:

您必须使用
文档。CreateElements(“http://www.w3.org/2000/svg“,“svg”)
而不是
document.createElement('svg')

document.querySelector('#circle svg').setAttribute('viewBox','190 20');
让svg=document.createElements(“http://www.w3.org/2000/svg“,”svg“,
圆圈=document.createElements(“http://www.w3.org/2000/svg“,”圆圈“);
circle.setAttribute('cx',200);
circle.setAttribute('cy',200);
圆圈.setAttribute('r',10);
svg.setAttributeNS(“http://www.w3.org/2000/xmlns/“,”xmlns:xlink“,”http://www.w3.org/1999/xlink");
setAttribute('viewBox','190 20');
svg.appendChild(圆);
document.body.appendChild(svg);
//document.querySelector(“#圈生成svg”).setAttribute('viewBox','190 20')
svg{
边框:2个虚线#666;
宽度:200px;
高度:200px;
}
动态添加viewBox属性的现有svg:


生成的svg带有动态添加的viewBox属性:

但您首先并没有创建有效的svg元素。不能使用createElement创建SVG元素(这仅适用于HTML元素)。必须使用CreateElements并提供SVG名称空间作为第一个参数

let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
  circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');