javascript - Javascript 添加的动态 svg 元素不起作用

标签 javascript html svg

我真的很困惑。我有一个显示良好的静态 SVG 元素,但是当我从 Javascript 添加相同的元素时,它不显示。这是为什么??

<html>
   <head>
	<script type="text/javascript">
	    function doit()
		{
			var svgdiv = document.getElementById('svg1');
			for (var k = 1; k < 3; ++k)
			{
				var svg = document.createElement('svg');
				svg.setAttribute('width',100);
				svg.setAttribute('height',100);
				console.log(svg);
				var c = document.createElement('circle');
				c.setAttribute('cx',50);
				c.setAttribute('cy',50);
				c.setAttribute('r',40);
				c.setAttribute('stroke','green');
				c.setAttribute('stroke-width',4);
				c.setAttribute('fill','yellow');
				svg.appendChild(c);
				svgdiv.appendChild(svg);
			}
		}
		window.onload = doit;
	</script>
  </head>
  <body>
	<svg width="100" height="100">
	  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
	</svg>
      <div id="svg1"></div>
   </body>
</html>

最佳答案

使用

document.createElementNS('http://www.w3.org/2000/svg', 'svg')

代替

document.createElement('svg')

解释:

SVG 元素必须在 SVG 命名空间中创建,因此不能由 createElement 创建,而必须使用 createElementNS 提供 SVG 命名空间作为第一个参数。

createElement 基本上创建名为 svg 和 circle 的 html 元素,而不是 SVG 元素。

text/html 并没有真正的命名空间,因此 HTML 解析器在遇到 <svg> 时神奇地切换到 SVG 命名空间。元素。如果您将 mime 类型更改为某个 XML namespace ,例如http://www.w3.org/1999/xhtml/那么你需要根上的 xmlns 属性 <html>元素,也在 <svg> 上元素。

<html>
   <head>
	<script type="text/javascript">
	    function doit()
		{
			var svgdiv = document.getElementById('svg1');
			for (var k = 1; k < 3; ++k)
			{
				var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
				svg.setAttribute('width',100);
				svg.setAttribute('height',100);
				console.log(svg);
				var c = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
				c.setAttribute('cx',50);
				c.setAttribute('cy',50);
				c.setAttribute('r',40);
				c.setAttribute('stroke','green');
				c.setAttribute('stroke-width',4);
				c.setAttribute('fill','yellow');
				svg.appendChild(c);
				svgdiv.appendChild(svg);
			}
		}
		window.onload = doit;
	</script>
  </head>
  <body>
	<svg width="100" height="100">
	  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
	</svg>
      <div id="svg1"></div>
   </body>
</html>

关于javascript - Javascript 添加的动态 svg 元素不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27489143/

相关文章:

javascript - 在响应式 slider 中设置高度(jQuery Cycle)

javascript - JQuery 函数不会在页面加载时触发它仅在我刷新页面或再次重新访问同一页面后才起作用

javascript - 为什么 ChartJS 在移动浏览器上的页面滞后?

html - SVG 不使用类颜色?

javascript - 从异步回调函数将对象推送到本地数组

javascript - 数组构造和负数

javascript - 如何在数据网格的列标题和行中动态添加复选框?

Javascript防止默认操作

ios - Cordova 无法处理的具有线性渐变的 SVG - iOS

javascript - 如何以符合欧盟法律的方式使用 Google Analytics?