【问题标题】:dynamic svg element added by Javascript doesn't workJavascript添加的动态svg元素不起作用
【发布时间】:2014-12-15 16:59:04
【问题描述】:

我真的很困惑。我有一个显示良好的静态 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>

【问题讨论】:

    标签: javascript html svg


    【解决方案1】:

    使用

    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 解析器遇到 &lt;svg&gt; 元素时,它会神奇地切换到 SVG 命名空间。如果您将 mime 类型更改为某个 XML 命名空间,例如http://www.w3.org/1999/xhtml/ 那么你需要根 &lt;html&gt; 元素和 &lt;svg&gt; 元素上的 xmlns 属性。

    <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>

    【讨论】:

    • 很奇怪。为什么会出现第一个圆圈?我没有对 SVG 命名空间的任何引用。
    • 第一个圆圈出现是因为当浏览器在&lt;svg&gt; 元素中找到&lt;circle&gt; 元素时,它知道要使用哪个命名空间。它有上下文。根据定义,调用 createElement("circle") 在“默认”命名空间中创建新元素,对于浏览器来说,它是 HTML,而不是 SVG。
    猜你喜欢
    • 2018-09-28
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 2018-08-05
    • 2017-12-29
    • 2014-08-31
    相关资源
    最近更新 更多